【问题标题】:Python continuous writing failed [duplicate]Python连续写入失败[重复]
【发布时间】:2017-05-13 12:23:59
【问题描述】:

我想多次读写文件。但是方法失败了,它只写入最后修改的内容而不是所有修改的内容。

错误的程序

def openfile():
    txt = open("test.txt", "r")
    contents = txt.readlines()
    txt.close()
    return contents

def write_file(contents,f):
    old_contents = openfile()
    old_contents.insert(1,contents)
    contents = "".join(old_contents )
    f.write(contents)
    f.close()

text1 = open("test.txt","w")
contents= "test1 \n"
write_file(contents,text1)

text2 = open("test.txt","w")
contents = "test2 \n"
write_file(contents,text2)**

担心输出

test2

我的希望输出

test1
test2

【问题讨论】:

  • 我不明白,您在问题中发布了答案?
  • 尝试使用“a”标志而不是“w”
  • 我只是想知道为什么第一种方法是担心
  • 只打开和关闭文件一次。
  • @K.Suthagar 以追加模式打开文件当然是执行此操作的正确方法。但是,OP 询问为什么他们目前的方法不起作用,所以我不会将这个问题作为您链接的问题的副本来结束。

标签: python


【解决方案1】:

text1 = open("test.txt","w")

这是因为上面的代码重置了内容。 “w”是覆盖文件内容。

下面的代码应该解释你哪里出错了-

def openfile():
    txt = open("test.txt", "r")
    contents = txt.readlines()
    print "Openfile method- Contents: "+str(contents)
    txt.close()
    return contents

def write_file(contents,f):
    print "WriteFile method- Content received: "+str(contents)
    old_contents = openfile()
    print "Writefile method- Old content read from file: "+str(old_contents)
    old_contents.insert(1,contents)
    print "Writefile method- Old content after insertion: "+str(old_contents)
    contents = "".join(old_contents )
    print "WriteFile method- Content to write: "+str(contents)
    f.write(contents)
    f.close()

text1 = open("test.txt","w")
contents= "test1 \n"
write_file(contents,text1)

text2 = open("test.txt","w")
contents = "test2 \n"
write_file(contents,text2)

如前所述,使用“a”附加到文件。

【讨论】:

    【解决方案2】:

    您“担心输出”的原因是您在函数外部以写入模式打开“test.txt”后,在openfile 内以读取模式重新打开它。当您以写入模式打开文件时,它会被截断,即文件指针定位到文件的开头,并且文件的当前内容被丢弃。因此,当您在 write_file 中调用 openfile 时,文件为空,因此 openfile 返回一个空列表。

    这是您的代码的修复版本。我们在openfile 中使用try... except,因此如果文件不存在,我们可以返回一个空列表。

    def openfile(fname):
        try:
            f = open(fname, "r")
            contents = f.readlines()
            f.close()
            return contents
        except FileNotFoundError:
            return []
    
    def write_file(contents, fname):
        old_contents = openfile(fname)
        old_contents.insert(1,contents)
        contents = "".join(old_contents)
        f = open(fname, "w")
        f.write(contents)
        f.close()
    
    contents= "test1 \n"
    write_file(contents, "test.txt")
    
    contents = "test2 \n"
    write_file(contents, "test.txt")
    

    这是运行该代码后“test.txt”的内容:

    test1 
    test2 
    

    其实打开文件时最好使用with:

    def openfile(fname):
        try:
            with open(fname, "r") as f:
                contents = f.readlines()
            return contents
        except FileNotFoundError:
            return []
    
    def write_file(contents, fname):
        old_contents = openfile(fname)
        old_contents.insert(1,contents)
        contents = "".join(old_contents)
        with open(fname, "w") as f:
            f.write(contents)
    

    然而,一个更好的方法是简单地以附加模式打开文件,正如 hiro protagonist 和 K.Suthagar 已经展示的那样。但我认为最好解释一下为什么您当前的代码没有按照您的预期执行。

    【讨论】:

      【解决方案3】:

      如python doc 中所述,如果要附加到现有数据,则需要使用mode='a' 打开文件; mode='w' 只是覆盖:

      with open(file='_test.txt', mode='a') as file:
          file.write('test')
      

      (如果您使用的是python 2,请将上面的变量名file更改为其他名称;在python 2中file是一个关键字)。

      【讨论】:

        【解决方案4】:

        文件打开和写入的代码太多,您可以使用以下几行将文本附加到文件中

        def FileSave(filename,content):
            with open(filename, "a") as myfile:
                myfile.write(content)
        
        FileSave("test.txt","test1 \n")
        FileSave("test.txt","test2 \n")
        

        这里,当我们使用open(filename, "a")这一行时,a表示附加文件,这意味着允许在现有文件中插入额外的数据

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-05-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多