【发布时间】:2018-08-02 01:16:15
【问题描述】:
我有一个文件夹,其中包含 425 个类似文件的列表,名为“00001q1.txt、00002w2.txt、00003e3.txt... 00425q1.txt”。每个文件在两行之间包含一行文本。这些行在所有文件中都是不变的。我需要提取这些行并将其作为行列保存到输出文件中。
这是一个能够循环文件夹中所有文件的脚本,但它不会从文件列表中提取所需的行到 otput 文件。
#!/usr/bin/python
# Open a file
import re
import os
import sys
import glob
outfile = open("list7.txt", "w")
# This would print all the files and directories (in sorted order)
full_path = r"F:\files\list"
filelist = sorted(os.listdir( full_path ))
print filelist
# This would scan the filelist and extract desired line that located between two rovs:
# 00001q1.txt:
# Row above line
# line
# Row under line
buffer = []
for line in filelist:
if line.startswith("Row above line"):
buffer = ['']
elif line.startswith("Row under line"):
outfile.write("".join(buffer))
buffer = []
elif buffer:
buffer.append(line)
# infile.close()
outfile.close()
如果我在脚本中定义了一个文件(例如 00001q1.txt“)而不是文件列表,则所需的行将成功写入输出文件。我应该怎么做那个脚本扫描文件列表?
提前致谢。
【问题讨论】:
-
你应该有 2 个嵌套循环:
for file in filelist:和for line in open(file):。
标签: python string python-2.7 file find