I am new to programming and I wanted to find an explanation for something I found odd in VS Code.
I was trying to execute a piece of Python script that looks functional, but found the error “No such file or directory” when I “Run” the code. The code involves reading a csv file and I tried to use different formats of relative and direct reference for the csv file to no success, so I turned the csv file into a text file and tried to do the same. The odd thing is the code only executed when I “Run and Debug” it using Python Debugger.
You can see below the lines I was stuck on when I tried “Run” with the csv reading lines commented out because it was not working:
# csv_read_path = 'TherJPR_Drugs.csv'
# with open(csv_read_path, 'rb') as csv_read:
# txt = csv.reader(csv_read)
txt_path = 'TherJPR_Drugs.txt'
with open(txt_path, encoding='utf-8-sig') as f: # the utf-8-sig handles UTF-8 with BOM encoding
txt = f.read().splitlines() # the splitlines() get rid of the n at the end of lines
The error generated was:
with open(txt_path, encoding=’utf-8-sig’) as f: # the utf-8-sig handles UTF-8 with BOM encoding
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: ‘TherJPR_Drugs.txt’
My main question: Why do I get this error on “Run” but not on “Run and Debug” with Python Debugger?
But also, the csv reading code lines seem to work on “Run and Debug” but for the for loop a few lines below that makes use of the csv.reader output already saved in a variable (txt). I get an error at the beginning of the for loop that shows “readline of closed file”:
ValueError after csv.reader
And when I tried to place the for loop (and a couple lines between the csv.reader and the for loop) within the “with open(…” block for the csv.reader function, I get the following error:
ValueError 2 on for loop
It says the file needs to be opened as text, but there has to be a way to read it as csv, right?
I’m sure I’m missing something.
I would appreciate your help on this.
Thanks,
Simon
SimonsWorld is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.