python搜索并写入文件

时间:2012-02-16 08:28:30

标签: python

在下面的代码中,我试图替换其中包含以下内容的文件的内容。 hellohello world和字符串hellohello应该用hello替换并写回文件.Ho来解决这个问题

  #!/usr/bin/python
  import os

  new_file_list=[]
  all_files=os.listdir("/tmp")
  for ff in all_files:
     if ff.endswith(".txt"):
        new_file_list.append(ff)

  for files in new_file_list:
     if files == "a.txt":
       print "======================================="
       file_name="/tmp/"+str(files)
       print file_name
       f=open(file_name ,"rw")
       while True:
         print "======================================="
         for line in f.readline():
            print line
            print "======================================="
            f.write(line.replace("hellohello","hello"))
            print line
         else:
            break
       for line in f.readline():
         print line

  f.close()

5 个答案:

答案 0 :(得分:1)

您无法写入文件的中间位置。最简单的解决方案是将文件读入内存,替换文本然后将其写回。

with open('file_name') as f:
    text = f.read()

text = text.replace('hellohello', 'hello')

with open('file_name', 'w') as f:
    f.write(text)

答案 1 :(得分:1)

执行简单任务的最简单方法是从文件中读取所有数据,执行替换,然后将新数据写入文件。

以下是您尝试执行的操作的示例代码:

filename = "/tmp/a.txt"
with open(filename, 'r') as f:
  data = f.read()
with open(filename, 'w') as f:
  f.write(data.replace("hellohello", "hello"))

答案 2 :(得分:1)

您可以使用fileinput模块替换文件中的字符串(无需打开两个文件或打开同一文件两次或将整个文本文件加载到代码中的内存中)。

#!/usr/bin/python
import os
import fileinput

new_file_list=[]
all_files=os.listdir("/tmp")
for ff in all_files:
 if ff.endswith(".txt"):
    new_file_list.append(ff)

for files in new_file_list:
 print files
 if files == "a.txt":
   print "======================================="
   file_name="/tmp/"+str(files)
   print file_name

   f = fileinput.FileInput(file_name, inplace=1)

   print "======================================="
   for line in f:
        line = line.replace("hellohello","hello")
        print line,
   f.close()

答案 3 :(得分:0)

读取整个文件然后回写文本的替代方法,可以使用临时文件。

您可以在阅读时逐行写入临时文件,最后用临时文件替换您的原始文件:

import shutil

filename = 'a.txt'
temp = 'copy.tmp'
with open(filename, 'r') as input_file, open(temp, 'w') as output_file:
    for line in input_file:
        output_file.write(line.replace('hellohello','hello'))

shutil.move(temp, filename)

答案 4 :(得分:0)

你应该真正努力改善代码imo。首先处理文件时,我建议尽可能使用os模块,而不是使用字符串连接。

所以代替:file_name="/tmp/"+str(files)你可以做os.path.join('/tmp', files)。您还可以使用name, extension = os.path.splitext(ff)获取文件扩展名,然后您可以测试扩展程序是否符合您的要求。

同样从算法的角度来看,我不明白为什么要迭代目录中的所有文件,将它们放在列表中,然后再次遍历该列表以进行处理。你也可以这样做:

   for ff in os.listdir('/tmp'):
       if os.path.splitext(ff)[1] == ".txt":
           file_n = os.path.join('/tmp', ff)
           with open(file_n, 'r') as file_p:
               text = file_p.read().replace('hellohello world', 'hello world')
           with open(file_n, 'w') as file_p:
               file_p.write(text)

这应该是你所需要的全部。