不同目录下有同名的不同文件。在这些文件中有些行几乎相等,我只想取出这些行的最后一行(后面还有更多行)并将其写入另一个文件中。
到目前为止我所做的:
#!/usr/bin/env python
import os
def cd_grep():
for file in os.listdir("."):
if os.path.isfile(file):
for line in open("graph.txt"):
if " 4.49" in line:
line_list=[line]
g = open('comparation','a')
g.write ("%s" % (line[0:4]))
g.close()
os.chdir('4.294')
cd_grep()
os.chdir(os.pardir)
os.chdir('4.394')
cd_grep()
os.chdir(os.pardir)
os.chdir('4.494')
cd_grep()
os.chdir(os.pardir)
os.chdir('4.594')
cd_grep()
os.chdir(os.pardir)
os.chdir('4.694')
cd_grep()
我创建了一个列表,因为我只想获取整行的特定信息。
最后我发现这个过程仅适用于小文件,并且仅当文件的最后一行包含我正在搜索的术语时。
对于大文件,我收到此消息(在文件内,我希望得到该行):
自愿上下文切换:3403
任何想法或建议将不胜感激。
最佳答案
不确定您收到的错误(在上次编辑后)。
我尝试稍微重写一下代码,希望它能给您一个与您需要的类似的结果(警告:未经测试)。
with open ('comparation', 'a') as write_file:
for path, dirs, files in os.walk(os.getcwd()):
for filename in [f for f in files if f == "graph.txt"]:
filepath = os.path.abspath(os.path.join(path, filename))
with open(filepath) as f:
for line in f:
if " 4.49" in line:
last = line
write_file.write("File: %s, Line: %s\n" % (filepath, last[0:4]))
关于python - 如何使用 python 在具有许多相似行的大文件中获取特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6063669/