I am fairly new to Python and I am trying to learn how to read and write csv files.I am programming on my iPad using Pythonista and I’ve encountered a problem I cant seem to solve. I want to read a csv file of which I don’t know the directory because of the limited iOS File Management App. The csv file is in the same folder where my python file is. I’ve found on google that I can find the absolute directory by using the following code:
import os
print(os.path.abspath("google_stock_data.csv"))
Which spits out:
/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/google_stock_data.csv
Alright now on to my problem:
import csv
path = "/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/google_stock_data.csv"
file = open(path, newline= '')
reader = csv.reader(file)
header = next(reader)
data = [row for row in reader]
print(header)
print(data[0])
The upper code gives me the error:
FileNotFoundError: [Errno 2] No such file or directory: '/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/google_stock_data.csv'
I know that the file exists and the directory should be correct since I’ve also tried finding it with pathlib and it turned out to be the same.
So what seems to cause the problem?
The problem lies within how I named my file. The name of the csv file that I wanted to open was called "google_stock_data.csv". Note that this is the filename and does not contain its file suffix at the end (which would be ".csv").
If you want to use file = open(...)
you have to also add the file suffix at the end of the filename.
This means that this is how it should look like in my case:
file = open('google_stock_data.csv.csv', newline= '')
Finding the absolute path with print(os.path.abspath("enter_file_name"))
is not needed if you have the file in the folder where your code is.If you do, for whatever reason, dont forget to add the file suffix at the end.
As for how to output anything from the file both my code and
with open(path, 'r', encoding='utf-8') as reader:
reader = csv.DictReader(reader)
for row in reader:
# ...do stuff
from @Michael M. work perfectly fine if you add .csv
at the end of where you declare path
.