在 Dropbox 上读取 CSV 文件而无需下载

Read a CSV file on Dropbox without downloading it

我正在开发一个应用程序,用户可以在其中提供下拉框文件和访问令牌的路径并查看文件的内容。是否可以只读取文件内容而不实际下载它。

import dropbox
import tempfile
import csv

dbx = dropbox.Dropbox(<access_token>)

metadata, f = dbx.files_download('/test/MOCK_DATA.csv')

filename = tempfile.NamedTemporaryFile(suffix='.csv').name

with open(filename, 'wb') as file:
  file.write(f.content)

with open(filename) as file:
  csv_reader = csv.reader(file, delimiter=',')
line_count = 0
for row in csv_reader:
  if line_count == 0:
    print(f'Column names are {", ".join(row)}')
    line_count += 1
  else:
    print(row)
    line_count += 1
print(f'Processed {line_count} lines.')

目前我可以阅读内容,但只能在下载后才能阅读。

使用 files_download 是使用 Dropbox Python SDK 访问文件数据的正确方法。然后在您的代码中将文件数据写入本地文件,但这不是必需的。

csv.reader 方法记录为:

csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.

所以你可以这样做:

import dropbox
import csv

dbx = dropbox.Dropbox(<access_token>)

metadata, f = dbx.files_download('/test/MOCK_DATA.csv')

csv_reader = csv.reader(f.content.decode().splitlines(), delimiter=',')

line_count = 0
for row in csv_reader:
    if line_count == 0:
        print(f'Column names are {", ".join(row)}')
        line_count += 1
    else:
        print(row)
        line_count += 1

print(f'Processed {line_count} lines.')