python - 在 Python 中创建新的文本文件?

标签 python file

有没有一种方法可以在不以“w”或“a”模式打开文本文件的情况下创建文本文件?例如,如果我想以“r”模式打开一个文件,但该文件不存在,那么当我捕获 IOError 时,我想创建一个新文件 例如:

while flag == True:
try:

    # opening src in a+ mode will allow me to read and append to file
    with open("Class {0} data.txt".format(classNo),"r") as src:

        # list containing all data from file, one line is one item in list
        data = src.readlines()

        for ind,line in enumerate(data):

            if surname.lower() and firstName.lower() in line.lower():
                # overwrite the relevant item in data with the updated score
                data[ind] = "{0} {1}\n".format(line.rstrip(),score)
                rewrite = True

            else:
                with open("Class {0} data.txt".format(classNo),"a") as src: 
                    src.write("{0},{1} : {2}{3} ".format(surname, firstName, score,"\n"))


    if rewrite == True:

        # reopen src in write mode and overwrite all the records with the items in data
        with open("Class {} data.txt".format(classNo),"w") as src: 
            src.writelines(data)
    flag = False

except IOError:
    print("New data file created")
    # Here I want a new file to be created and assigned to the variable src so when the
    # while loop iterates for the second time the file should successfully open

最佳答案

一开始只需检查文件是否存在,如果不存在则创建它:

filename = "Class {0} data.txt"
if not os.path.isfile(filename):
    open(filename, 'w').close()

从此时起,您可以假设该文件存在,这将大大简化您的代码。

关于python - 在 Python 中创建新的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27460951/

相关文章:

javascript - odoo 10 扫描条形码并开始操作

javascript - 使用服务器端 Javascript 检查 Web 服务器上的文件是否存在

javascript - 如何通过将 AJAX 中的 <input type ="file"> 数据放入对象中来发送它?

python - 使用 tf.keras.application 时如何获得中间输出

c++ - 从文件末尾检索字符串时失败

file - 不同的文件格式存储方式不同

php读取产品数据txt文件

python - 基于多条件检查将值放在另一个数据框中的 pandas 数据框中的列中

python - 将 conda HDF4 链接到 conda GDAL(Anaconda Python)

python - 使用来自另一个数据帧的信息重新组合一个数据帧中的数据