Python 在 read() 之后无法从文本文件中读取行

bto*_*rge 1 python text file

我有一个问题,我试图首先检查文本文件是否存在已知字符串,然后基于此循环该文件并插入不同的行。

由于某种原因,在调用 file.read() 检查测试字符串后,for 循环似乎不起作用。我尝试调用 file.seek(0) 返回到文件的开头,但这没有帮助。

我当前的代码如下:

try:
  f_old = open(text_file)
  f_new = open(text_file + '.new','w')
except:
  print 'Unable to open text file!'
  logger.info('Unable to open text file, exiting')
  sys.exit()
wroteOut = False

# first check if file contains an test string
if '<dir>' in f_old.read():
  #f_old.seek(0)  # <-- do we need to do this??
  for line in f_old: # loop thru file
    print line
    if '<test string>' in line:
      line = '    <found the test string!>'
    if '<test string2>' in line: 
      line = '  <found test string2!>' 
    f_new.write(line) # write out the line
  wroteOut = True # set flag so we know it worked
f_new.close()
f_old.close()    
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

你已经知道答案了:

#f_old.seek(0)  # <-- do we need to do this??
Run Code Online (Sandbox Code Playgroud)

是的,您需要先查找到文件的开头,然后才能再次读取内容。

所有文件操作都使用当前文件位置。使用file.read()读取所有文件,将当前位置设置为文件末尾。如果您想从文件开头重新读取数据,则file.seek(0)需要进行调用。替代方案是:

  • 不再读取文件,您只是读取了所有数据,因此请使用该信息。文件操作很慢,使用内存中的相同数据要快得多:

    contents = f_old.read()
    if '<dir>' in contents:
    for line in contents.splitlines():
        # ....
    
    Run Code Online (Sandbox Code Playgroud)
  • 重新打开文件。以读取模式打开文件会将当前文件位置放回开头。