我想打开并读取特定文件夹中的所有csv文件.我使用的是OS X El Capitan版本10.11.6,我正在使用Python 2.7.10.我在phyton文件中有以下功能:
def open_csv_files(dir):
for root,dirs,files in os.walk(dir):
for file in files:
if file.endswith(".csv"):
f= open(file)
print "FILE OPEN, AND DO SOMETHING... "
f.close
return
Run Code Online (Sandbox Code Playgroud)
我打电话 open_csv_file(./dati/esempi)
此程序返回
IOError: [Errno 2] No such file or directory: 'sensorfile_1.csv'
Run Code Online (Sandbox Code Playgroud)
我尝试用绝对路径调用该过程,/Users/Claudia/Desktop/Thesis/dati/esempi/但我有同样的错误.
另外我定义了另一个打印文件夹中所有文件名的程序,这个程序正确打印文件夹中的所有文件名.
谢谢您的帮助.
您需要根据root(基础目录)和文件名的值构建文件的绝对路径.
import os
def open_csv_files(directory):
for root, dirs, files in os.walk(directory):
for file_name in files:
if file_name.endswith(".csv"):
full_file_path = os.path.join(root, file_name)
with open(full_file_path) as fh:
print "Do something with", full_file_path
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3073 次 |
| 最近记录: |