Reputation: 33
The problem I have is my text file adds empty lines every now and then, which makes my program not work as intended. I was wondering if from these two parts there is something which makes this happen in my code or if there is a way to remove these empty rows from the file or still make it work, even if they exist in the file.
def results_from_file(file_name):
my_file = open(file_name, "r")
data = my_file.read().split("\n")
results = []
for row in data:
results.append(row.strip(";").split(";"))
return results
def save_results_to_file(file_name, results):
my_file = open(file_name, "w")
for result in results:
my_file.write("{}\n".format(";".join(result)))
my_file.close()
print("\nResultatet är nu sparat i filen!")
Upvotes: 0
Views: 771
Reputation: 26201
I'm not sure if you are worried about getting empty results from reading a file that has empty lines, or writing in a way that produces empty lines, but here is a relatively bullet-proof way to ensure neither can happen:
def results_from_file(filename):
with open(filename, 'r') as f:
results = [[r.strip() for r in line.split(';')] for line in f]
results = [[r for r in row if r] for row in results if row]
return [row for row in results if row]
def save_results_to_file(filename, results):
with open(filename, 'w') as f:
for parts in results:
if parts:
f.write(';'.join([res for res in parts if res]) + '\n')
Example:
# setup
filename = 'foo'
txt = """line 1 res 0;;; line1 res 1; line 1 res 2
line 2 res 3; ; line2 res 4;
line 3 res 5
line 5 res 6
"""
with open(filename, 'w') as f:
f.write(txt)
# 2. test read
results = results_from_file(filename)
# results:
[['line 1 res 0', 'line1 res 1', 'line 1 res 2'],
['line 2 res 3', 'line2 res 4'],
['line 3 res 5'],
['line 5 res 6']]
# 3. mess up purposely the results
results.insert(2, [])
results.insert(0, [])
# results:
[[],
['line 1 res 0', 'line1 res 1', 'line 1 res 2'],
['line 2 res 3', 'line2 res 4'],
[],
['line 3 res 5'],
['line 5 res 6']]
# 4. write to file with filtering
save_results_to_file(filename, results)
# check:
! cat $filename
line 1 res 0;line1 res 1;line 1 res 2
line 2 res 3;line2 res 4
line 3 res 5
line 5 res 6
Upvotes: 1
Reputation: 556
Since the code snippet is really small and very dependent on other things i can just give general advice
with open(file_name, "r") as input_file:
This will make sure the file is closed in the end, and much cleaner
2.Since you are going line by line anyway, you can just iterate over the lines directly from the file instance
with open(file_name, "r") as input_file:
for line in input_file:
pass
3.The place i can think of that will create empty lines in an empty result in results
. I would filter empty results before writing them, additionally you would need to debug the code creating the results to find the cause of the empty lines issue
for result in results:
if result.strip() != "":
my_file.write("{}\n".format(";".join(result)))
Upvotes: 0