'How can I iterate through every line in a text file then save the lines that come back with the correct output to separate text file?
I am working on a program and need some assistance. Essentially the part of the program I'm working on opens a text file and iterates through each line of the file to basically see whether or not that line in the file is either valid or invalid.
The problem I'm having is, I can't get the lines that come back valid to save to a separate text file than. I've tried different varriations of for loops if statements and T/F and no luck.
For example:
Try:
good = 'valid'
f = open('xxx.txt', 'r')
f2 = open('yyy.txt', 'a')
list = open('xxx.txt').readlines()
for i in list:
f.readlines()
try:
url = 'https://zzz.com/' + i
html = requests.get(url).text
data = json.loads(html)
print(data.get('').get(''))
time.sleep(5)
if i in list == good:
f2.writelines()
Solution 1:[1]
You can do something like below to select particular lines from one file and write them in another:
good = "valid"
valid_lines = []
with open("input_file.txt", 'r') as f:
input_lines = f.readlines()
for line in input_lines:
if line.startswith(good):
valid_lines.append(line)
with open("output_file.txt", 'a') as f:
f.writelines(valid_lines)
For input file:
aaa
valid1
bbb
valid2
ccc
It creates an output file with:
valid1
valid2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dan Constantinescu |
