After writing a function to generate some data, I wanted to add the ability to save it. I initially started out with the following code which I ran with 'save=True':
[in]
import csv
... (main body of code - all this works fine)
if save is True:
print("Saving...")
with open('dataset.csv', 'a+') as f:
lines = f.readlines()
for line in lines:
linesplit = line.split(",")
name_in_dataset = linesplit[0]
...
(... some code for the actual saving process - irrelevant)
print("Data added successfully")
[out]
Saving...
I know that the dataset file contains this name and should have saved here, so I was a little confused as to where it went wrong. I started to break down the code until I reached this:
[in]
if save is True:
print("Saving...")
with open('dataset.csv') as f:
lines = f.readlines()
print(lines)
[out]
Saving...
[]
Not really sure why it can't read the lines? I though I had used the same code previously to read the lines of this very file so I'm really confused about why it's not working now.
I've tried adding things to the code such as f.seek(0)
but this has made no difference. I've also tried changing the open function to 'a'
and 'r'
but alas it can't read the lines. I've searched through so many posts about .readlines()
and can't find anyone experiencing this :( I feel like I've just been at work for too long and have forgotten the basic fundamentals of Python coding!
Thanks in advance <3
EDIT: Using the suggestions in the comments I changed the code to:
with open('(file path)/dataset.csv', 'r') as f:
f.seek(0)
lines = csv.reader(f)
print(lines)
and it returned:
Saving...
<csv.reader object at 0x7f01282c7f20>