简体   繁体   中英

How do I read a csv file with Pythonista using an IPad?

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?

Try using the with open() (read) syntax. I have something very similar and this works for me. Your path is correct.

with open(path, 'r', encoding='utf-8') as reader:
        reader = csv.DictReader(reader)
        for row in reader: 
            # ...do stuff

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM