繁体   English   中英

如何在 Python 中同时打开多个文件?

[英]How can I open multiple files at the same time in Python?

我正在尝试打开多个“.csv”文件,但它一直在输出“OSError:rec_11.csv not found”(实际文件无关紧要。它总是停在 3)。 我知道文件在那里,我可以自己打开它。 前两个文件打开得很好,我可以获取数据,但无论我放什么文件,它总是停在第三个文件上。 从我发现这应该可以工作,但它没有:

def extract(file):
    data =np.genfromtxt(file,delimiter=",")
    arr = data.transpose()
    return arr[2]

directory = r'C:\Users\...\Desktop\senior\Peeps'

for subdir, dirs, files in os.walk(directory):
    for file in files:
        print(os.path.join(subdir, file))
        if(file.endswith(".csv")):
            people.append(os.path.join(subdir, file))
            ecg_data.append(extract(file))

我也试过这个:

for filename in os.listdir(directory):
        print(filename)
        if(filename.endswith(".csv")):
            ecg_data.append(extract(filename))
            people.append(filename)

我应该注意到 Peeps 里面有多个文件夹,里面是 csv 文件。

解决了 有人向我指出,我需要加入目录和文件。 以下内容现在对我有用。

for subdir, dirs, files in os.walk(directory):
    for file in files:
        if(file.endswith(".csv")):
            people.append(os.path.join(subdir, file))
            ecg_data.append(extract(os.path.join(subdir, file)))

试试下面的代码:

path=os.getcwd() # Obtains your current working directory
path_list = []
valid__extensions = [".csv"] #specify your vaild extensions here
valid_extensions = [item.lower() for item in valid_extensions]
for file in os.listdir(path):
    extension = os.path.splitext(file)[1]
    if extension.lower() not in valid_extensions:
        continue
    path_list.append(os.path.join(path, file))

for csv_file in path_list:
# add what ever function you like to your .csv file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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