2014-03-26 311 views
0

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

为了在每一个字之间放“”我用这个命令

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) 

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

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

添加新单词的代码完美地工作。但我认为应该有一种更简单的方法来打开文件,一次做两次编辑并保存。但我不太确定。我花了大量的时间来弄清楚如何覆盖文件,这是我寻求帮助的时间

回答

0

在这里你去:

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' 
+0

对不起,但你给我的任何代码都不适合我。它们都不会在每个单词之间产生带有“,”的输出。他们只在每一行的末尾添加'yes'来产生输出。所以基本上输出和我的第三个代码一样。 – user3072782

+0

哎呀!很容易修复... – Broseph

+0

固定。谢谢 – user3072782

0

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

writable = open('configuration', 'w') 

打开您的文件,然后把更改的行与

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

到文件。 希望有所帮助 - 即使是一点点。 ;)

0

对于第一个问题,您可以在覆盖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()。

+0

我的第二个代码,即在每一行添加新词并保存文件完美。但是我想在每个单词之间添加“,”,然后在每个文件的末尾添加一个新单词,而不必打开和关闭文件两次。 – user3072782

+0

你可以做类似'source = open('myfile','r +')txt = source.read()。replace(“\ n”,“yes \ n”)source.seek(0)source.write txt)source.truncate()source.close()'。 –