Python连续写入失败

这个问题在这里已经有了答案:

  • 你如何追加到一个文件? 8个答案

  • 这对于文件打开和写入来说代码太多了,您可以使用以下几行将文本追加到文件中

    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表示附加文件,这意味着允许插入额外的数据到现有的文件


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

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

    (如果您使用的是Python 2,则将上面的变量名称file更改为其他内容;在python 2 file是关键字)。


    之所以你的“忧虑输出”是你重新打开“的test.txt”在读模式里面openfile你已经在职能以外的写入模式打开后它。 当您在写入模式下打开文件时,它会被截断,即文件指针位于文件的开头,文件的当前内容将被丢弃。 所以当你在write_file里面调用openfile时,这个文件是空的,因此openfile返回一个空列表。

    这是您的代码的修复版本。 我们使用try... except 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主角和K.Suthagar已经显示。 但我认为这是一个好主意,可以解释为什么你当前的代码没有达到你期望的效果。

    链接地址: http://www.djcxy.com/p/42413.html

    上一篇: Python continuous writing failed

    下一篇: How to get Python to print primes into a text file?