have different files with same name, in different directories. In these files there are lines which are almost equal, I would like to take out only the last line of these ones( there are more lines after it) and write it in another file.
So far what I have done:
#!/usr/bin/env python
import os
def cd_grep():
for file in os.listdir("."):
if os.path.isfile(file):
for line in open开发者_如何学Go("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()
I've created a list because I am gonna take only a specific information of the whole line.
Finally I got that this procedure only works for small files and only if the last line of the file contains the term I'm searching. For big files, I got this message ( inside the file, which I was hoping to get the line):
Voluntary context switches: 3403Any idea or suggestion will be very appreciate.
Not sure about the error you are receiving (after your last edit).
I have tried to rewrite the code a bit, hope it gives you a result similar to what you need (WARNING: not tested).
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]))
I'm guessing you aren't closing your files.
def cd_grep():
for file in os.listdir("."):
if os.path.isfile(file):
graph_file = open('graph.txt'):
for line in graph_file:
if " 4.49" in line:
line_list=[line]
graph_file.close()
g = open('comparation','a')
g.write ("%s" % (line[0:4]))
g.close()
Or much better use with
to open (and always close) your files.
def cd_grep():
for file in os.listdir("."):
if os.path.isfile(file):
with open('graph.txt') as graph_file:
for line in graph_file:
if " 4.49" in line:
line_list=[line]
with open('comparation','a') as g:
g.write ("%s" % (line[0:4]))
精彩评论