Reading a text file line by line, if the line contains a specific string I want to add that entire line a separate text file
# read in the file
file = open("/home/jimmy/python/test.txt", "r")
# create an empty list to hold the good lines
good_lines = []
# check each line of the file and filter which to keep
for num, line in file:
if " A" in line:
num = str(num)
good_lines.append(num)
f = open("goodline.txt", "w")
f.write(str(good_lines))
f.close()
'''
Not sure what is wrong. I am also not totally sure how to use that specific type of for loop with the comma.
Error I'm getting is the for loop line
ValueError: too many values to unpack (expected 2)
CodePudding user response:
That is a lot of code for one task in which Python can be quite expressive.
In particular one can pass to a call to "writelines" in the output file a generator expression - a very handy nice construct which allows for mapping and filtering in a stream in a simple expression (and we don't even need mapping in this case).
open("output file.txt", "wt").writelines(
line for line in open("input file.txt")
if " A" in line)
)
(Yes, that is all the code you need for this task, and will run as is: just replace the file names as needed)
CodePudding user response:
In testing out your code and doing some tweaks, you might try out this code snippet.
# read in the file
test_file = open("test.txt", "r") # You might change this to have an absolute path
# create an empty list to hold the good lines
good_lines = []
# check each line of the file and filter which to keep
for test_line in test_file:
if " A" in test_line:
good_lines.append(test_line)
f = open("goodline.txt", "w")
for item in good_lines:
f.write(str(item))
f.close()
The following was the text in the test file.
A good line
Another good line
Not a good line
Also not a good line
And this was the data in the created output file.
A good line
Another good line
Give that a try and see if it meets the spirit of your project.
CodePudding user response:
You can try the code below to see if it gets the correct output.
# read in the file
file = open("/home/jimmy/python/test.txt", "r")
# parses the lines in the text file
lines = file.readlines()
# create an empty list to hold the good lines
good_lines = []
# check each line of the file and filter which to keep
for line in lines:
if " A" in line:
num = str(line)
good_lines.append(num)
f = open("goodline.txt", "w")
f.write(str(good_lines))
f.close()