#first read everything
with open('file_name','r') as f:
content = f.read()
#now perform modifications
content = content.replace('foo 69','')
#now write back to the file
with open('file_name','w') as f:
f.write(content)
现在,我对代码中的一些问题进行了评论:
^{pr2}$
编辑-如注释中所述,如果文件很大,并且您不想阅读所有内容。在
最好的方法是逐行读取内容,并将内容写入另一个文件(不包括要删除的行)。在
to_replace = 'foo 69\n' #note \n is neccessary here
with open('input.txt','r') as input_file:
with open('ouput.txt','w') as output:
for line in input_file:
if line!=to_replace:
output.write(line)
#Now, let's say you want to delete all the contents of the input_file
#just open it in write mode and close without doing anything
input_file = open('input_file.txt','w')
input_file.close()
# If you want to delete the entire input_file and rename output_file to
# original file_name then you can do this in case of linux OS using subprocess
subprocess.call(['mv', 'output_file.txt', 'input_file.txt'])
这是非常节省内存的,因为在任何时间点内存中只有一行内容。input_file只是指向文件的指针,迭代-for line in input_file不会读取整个文件并开始逐个迭代内容。在
正确的方法是首先完全读取内容,进行修改,然后写回文件。在
这种方法也很简洁易读。在
现在,我对代码中的一些问题进行了评论:
^{pr2}$编辑-如注释中所述,如果文件很大,并且您不想阅读所有内容。在
最好的方法是逐行读取内容,并将内容写入另一个文件(不包括要删除的行)。在
这是非常节省内存的,因为在任何时间点内存中只有一行内容。
input_file
只是指向文件的指针,迭代-for line in input_file
不会读取整个文件并开始逐个迭代内容。在我不确定您到底希望输出是什么样的(例如,如果您希望删除
bar 70
上的行),但这段代码实际上只是从文件中删除foo 69
。它只需打开对文件的引用一次:在下面的代码片段中,我使用
.
来代替换行符进行格式化。在
^{pr2}$contacts.txt
之前:contacts.txt
之后:相关问题 更多 >
编程相关推荐