Python-逐行读取文件并进行处理

时间:2018-12-12 18:17:03

标签: python

我想读取输入文件的行和行,以及该行是否包含一些字符 我想跳过该行并阅读下一行。除了跳过的行,其余所有行都需要写入输出文件。使用函数创建了以下代码,但输出文件中未写入行,有人可以让我知道错误/更正。

  import os
  import time 
  timestr = time.strftime("%Y%m%d-%H%M%S")
  inputfile_str='input.txt'
  outputfile_str='output.txt'
  directory = os.path.normpath("C:/Users/Desktop/Python/Input")

  FILE_NAME=inputfile_str
  file_identifier = 'input.txt'
  def writeroutine(line):
      print(line)
      for subdir,dirs,files in os.walk(directory):
        for file in files:
          if file==outputfile_str:
         outputfile.write(line)


for subdir,dirs,files in os.walk(directory):
   for file in files:
      outputfile = open("Output.txt",'w')
       if file==inputfile_str:
        f=open(os.path.join(subdir,file),'r')
        for line in f:
            if line[0:12] == "AAAAAAAAAAAA" or line[20:29] == "##### ##:":
                continue
            else:
                writeroutine(line)

3 个答案:

答案 0 :(得分:0)

应该在全局范围内声明输出文件变量。您已经在for循环中声明了。

答案 1 :(得分:0)

我想说的是您正在检查python中是否存在文件错误:

import os

inputfile_str = 'input.txt'
outputfile_str = 'output.txt'
directory = os.path.normpath("C:/Users/Desktop/Python/Input")

out_file = open( os.path.join(directory ,outputfile_str ), "w")
with open( os.path.join(directory ,inputfile_str ), "r") as f:
    for line in f:
        if line[0:12] == "AAAAAAAAAAAA" or line[20:29] == "##### ##:":
            continue
        else:
            out_file.write( line)

out_file.close()

如果您想在文件不存在的情况下捕获异常,则可以将所有内容(不良做法)或仅将文件打开行放在try语句中:

try:
    code_with_possible:exception
except Exception as r:
    handle_exception

例如

try:
    out_file = open( os.path.join(directory ,outputfile_str ), "w")
except FileNotFoundError as e:
    print( e)
    ...more_exception_handling

答案 2 :(得分:0)

您无需使其变得复杂。

bad_guys = ["AAAAAAAAAAAA", "##### ##:"]
with open('input.txt', 'r') as infile:
    with open('output.txt', 'a') as outfile: 
        for line in infile: 
            if (bad_guys[0] in line) or (bad_guys[1] in line):
                continue
            else: 
                outfile.write(line)