【问题标题】:Creating new text file in Python?在 Python 中创建新的文本文件?
【发布时间】:2015-02-12 04:27:38
【问题描述】:

有没有一种无需在“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

【问题讨论】:

标签: python file


【解决方案1】:

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

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

从这一点开始,您可以假设文件存在,这将大大简化您的代码。

【讨论】:

    【解决方案2】:

    没有操作系统允许您在不实际写入文件的情况下创建文件。你可以把它封装在一个库中,这样创建过程是不可见的,但是如果你真的想修改文件系统,就不可能避免写入文件系统。

    这是一个快速而肮脏的 open 替代品,可以满足您的建议。

    def open_for_reading_create_if_missing(filename):
        try:
            handle = open(filename, 'r')
        except IOError:
            with open(filename, 'w') as f:
                pass
            handle = open(filename, 'r')
        return handle
    

    【讨论】:

      【解决方案3】:

      如果文件不存在,最好创建文件,例如比如:

      import sys, os
      def ensure_file_exists(file_name):
          """ Make sure that I file with the given name exists """
          (the_dir, fname) = os.path.split(file_name)
          if not os.path.exists(the_dir):
               sys.mkdirs(the_dir) # This may give an exception if the directory cannot be made.
          if not os.path.exists(file_name):
               open(file_name, 'w').close()
      

      您甚至可以有一个 safe_open 函数,在打开读取并返回文件句柄之前执行类似的操作。

      【讨论】:

        【解决方案4】:

        问题中提供的示例代码不是很清楚,特别是因为它调用了多个未在任何地方定义的变量。但基于此,这是我的建议。您可以创建一个类似于 touch + file open 的函数,但它与平台无关。

        def touch_open( filename):
            try:
                connect = open( filename, "r")
            except IOError:
                connect = open( filename, "a")
                connect.close()
                connect = open( filename, "r")
            return connect
        

        如果文件存在,此函数将为您打开文件。如果文件不存在,它将创建一个具有相同名称的空白文件并打开它。 import os; os.system('touch test.txt') 的另一个额外功能是它不会在 shell 中创建子进程,从而使其更快。

        由于它不使用with open(filename) as src 语法,您应该记住在末尾使用connection = touch_open( filename); connection.close() 关闭连接,或者最好在for 循环中打开它。示例:

        file2open = "test.txt"
        for i, row in enumerate( touch_open( file2open)):
            print i, row, # print the line number and content
        

        此选项应优先于 data = src.readlines() 后跟 enumerate( data)(在您的代码中找到),因为它避免了在文件中循环两次。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-03
          • 1970-01-01
          • 2012-08-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多