【问题标题】:Edit and save file编辑和保存文件
【发布时间】:2014-03-26 01:32:56
【问题描述】:

我需要编辑我的文件并保存它,以便我可以将它用于另一个程序。首先,我需要在每个单词之间加上“,”,并在每行末尾添加一个单词。

为了在每个单词之间加上“,”,我使用了这个命令

for line in open('myfile','r+') :
    for word in line.split():
        new = ",".join(map(str,word)) 
        print new 

我不太确定如何覆盖原始文件或为编辑后的版本创建新的输出文件。我试过这样的事情

with open('myfile','r+') as f:
    for line in f:
        for word in line.split():
             new = ",".join(map(str,word)) 
             f.write(new)

输出不是我想要的(不同于 print new)。 其次,我需要在每一行的末尾添加一个单词。所以,我尝试了这个

source = open('myfile','r')
output = open('out','a')
output.write(source.read().replace("\n", "yes\n"))

添加新词的代码完美运行。但我在想应该有一种更简单的方法来打开文件,一次进行两次编辑并保存。但我不太确定如何。我花了很多时间来弄清楚如何覆盖文件,现在是我寻求帮助的时候了

【问题讨论】:

    标签: python file


    【解决方案1】:

    给你:

    source = open('myfile', 'r')
    output = open('out','w')
    output.write('yes\n'.join(','.join(line.split()) for line in source.read().split('\n')))
    

    单线:

    open('out', 'w').write('yes\n'.join(','.join(line.split() for line in open('myfile', 'r').read().split('\n')))
    

    或者更清晰:

    source = open('myfile', 'r')
    processed_lines = []
    for line in source:
        line = ','.join(line.split()).replace('\n', 'yes\n')
        processed_lines.append(line)
    output = open('out', 'w')
    output.write(''.join(processed_lines))
    

    编辑 显然我看错了一切,大声笑。

    #It looks like you are writing the word yes to all of the lines, then spliting
    #each word into letters and listing those word's letters on their own line? 
    source = open('myfile','r')
    output = open('out','w')
    for line in source:
        for word in line.split():
            new = ",".join(word)
            print >>output, new
        print >>output, 'y,e,s'
    

    【讨论】:

    • 很抱歉,您给我的代码都不适合我。它们都不会在每个单词之间产生带有“,”的输出。他们只在每行末尾添加了“是”的输出。所以基本上输出与我工作的第三个代码相同。
    • 实际上,在我摆脱 .split 并使用 join(line) 之后,您之前提供的代码运行良好。
    【解决方案2】:

    这个文件有多大? 也许您可以创建一个临时列表,其中仅包含您要编辑的文件中的所有内容。每个元素都可以代表一条线。 编辑字符串列表非常简单。 更改后,您可以使用

    再次打开您的文件
    writable = open('configuration', 'w')
    

    然后将更改的行放入文件中

    file.write(writable, currentLine + '\n')
    

    。 希望能有所帮助——哪怕是一点点。 ;)

    【讨论】:

      【解决方案3】:

      对于第一个问题,你可以在覆盖 f 之前读取 f 中的所有行,假设 f 以 'r+' 模式打开。将所有结果追加到一个字符串中,然后执行:

      f.seek(0)    # reset file pointer back to start of file
      f.write(new) # new should contain all concatenated lines
      f.truncate() # get rid of any extra stuff from the old file
      f.close()
      

      对于第二个问题,解决方案类似:读取整个文件,进行编辑,调用 f.seek(0),写入内容,f.truncate() 和 f.close()。

      【讨论】:

      • 我的第二个代码,即在每一行添加新单词并保存文件完美。但是我想在每个单词之间添加“,”,然后在每个文件的末尾添加一个新单词,而不必打开和关闭文件两次。
      • 你可以做类似source=open('myfile', 'r+') txt=source.read().replace("\n", "yes\n") source.seek(0) source.write(txt) source.truncate() source.close()的事情。