如何使用IPad用Pythonista读取csv文件?

问题描述 投票:1回答:1

我对Python相当陌生,我正试图学习如何读写csv文件,我正在使用Pythonista在iPad上编程,我遇到了一个问题,我似乎无法解决。我想读取一个我不知道目录的csv文件,因为iOS文件管理应用有限。csv文件在我的python文件所在的同一个文件夹里,我在google上发现,我可以通过使用下面的代码找到绝对目录。

import os print(os.path.abspath("google_stock_data.csv"))

吐出的代码是:

/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/google_stock_data.csv

好了,现在说说我的问题

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])

上面的代码给了我错误的提示

FileNotFoundError: [Errno 2] No such file or directory: '/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/google_stock_data.csv'

我知道这个文件是存在的,而且目录应该是正确的,因为我也试过用pathlib找到它,结果是一样的。

那么是什么原因导致了这个问题呢?

python ios csv ipad pythonista
1个回答
0
投票

尝试使用 with open() (read)语法。我有一个非常类似的东西,这对我来说是有效的。你的路径是正确的。

with open(path, 'r', encoding='utf-8') as reader:
        reader = csv.DictReader(reader)
        for row in reader: 
            # ...do stuff
© www.soinside.com 2019 - 2024. All rights reserved.