Reputation: 11
I recently got the marks for a program I wrote for an assignment and I almost failed. The assignment was to create an address book that a user could add to and amend, with some other features.
The issue was with the import of my .txt file as, when the marker tried to run it, it couldn't locate the file and therefore couldn't run. It ran with no issue for me, which is why I didn't spot it, and so I assume that there is an issue with finding the directory when run on another PC.
This is the code that failed me:
import csv
filepath = 'data.txt'
with open(filepath, newline='') as f:
reader = csv.reader(f)
data = list(reader)
I can see some smaller issues with this, e.g. I left 'newline' from some previous code that was changed, but I don't know what I should have done differently. I also don't think that the issue is with importing the .txt file as a CSV as this worked fine when writing and saving to the file on my PC.
Any help with this would be really appreciated.
Edit
I forgot to add that my uni gave a framework for importing the file (which I didn't use) which was this:
import os
save = False
last = -1
data = []
Not sure if this is helpful but thought it would be best to include it
Upvotes: 1
Views: 66
Reputation: 304
this error is common, thoses kind of error occur depending how you run your script. I tied to reproduce your problem, I indeed succeeded.
For exemple, I ran your script in the cmd and it gave me no errors. But when I ran it in my IDE with the"run function" I get the error "FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'"
.
This is really hard to fix because its not really your fault. You should really talk to your teacher about that. She will show you the wright way to do it.
Upvotes: 0
Reputation: 581
please give the correct path of file if you are trying for windows . and than to debug it further try to print the data value as below :
import csv
filepath = 'C:/Users/diwak/Desktop/config.txt'
with open(filepath, newline='') as f:
reader = csv.reader(f)
data = list(reader)
print(data)
Upvotes: 0
Reputation: 15105
Your code assumes that data.txt file exists. And crashes if it doesn't. Either you need to make very sure that you package data.txt together with your code and provide instructions to unpack them into the same directory or you need to handle it somehow. Maybe create it if it is missing.
Upvotes: 2