测试大文件是否存在的最佳方法

时间:2017-05-15 08:33:43

标签: python pandas exception operating-system large-files

我想知道什么是最有效的方法来测试本地是否存在大文件(不将其加载到内存中)。如果它不存在(或不可读),则下载它。目标是在pandas DataFrame中上传数据。

我编写了下面的代码片段(并使用小文件进行测试)。正确性和pythonic编程怎么样?

url = "http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv" # 4.7kB  
file = "./test_file.csv" 

try:
    os.open( file, os.O_RDONLY)
    df_data = pd.read_csv( file, index_col=0)

except: 
    df_data = pd.read_csv( url, index_col=0)
    df_data.to_csv( file)

3 个答案:

答案 0 :(得分:2)

我认为您可以使用try并抓住FileNotFoundError

url = "http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv" # 4.7kB  
file = "./test_file.csv" 

try:
    df_data = pd.read_csv(file, index_col=0)

except FileNotFoundError: 
    df_data = pd.read_csv(url, index_col=0)
    df_data.to_csv(file)

答案 1 :(得分:0)

您可以检查文件是否存在,如果不存在则从网址加载:

import os
import pandas as pd

url = "http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv"
f = "./test.csv"

if os.path.exists(f):
    df = pd.read_csv(f)
else:
    df = pd.read_csv(url)

答案 2 :(得分:0)

os.path.isfile(file)在我看来是最好的解决方案:在下载大文件之前检查:

if not os.path.isfile( file):
       urllib.urlretrieve(url, file)
df_data = pd.read_csv( file, index_col=0)

它比从url直接上传到内存(下载到磁盘然后上传到内存)慢,但在我的情况下更安全...
感谢所有人