[英]How can I open multiple files at the same time in Python?
I'm trying to open multiple ".csv" files but it keeps outputting "OSError: rec_11.csv not found"(actual file doesn't matter. It always stops at 3).我正在尝试打开多个“.csv”文件,但它一直在输出“OSError:rec_11.csv not found”(实际文件无关紧要。它总是停在 3)。 I know the file is there and I can open it by itself.我知道文件在那里,我可以自己打开它。 The first two files are opened fine and I can get the data but it always stops at the third one no matter what files I put in there.前两个文件打开得很好,我可以获取数据,但无论我放什么文件,它总是停在第三个文件上。 From what I have found this is supposed to work but it doesn't:从我发现这应该可以工作,但它没有:
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))
I have also tried this:我也试过这个:
for filename in os.listdir(directory):
print(filename)
if(filename.endswith(".csv")):
ecg_data.append(extract(filename))
people.append(filename)
I should note that inside Peeps there are multiple folders and inside those are the csv files.我应该注意到 Peeps 里面有多个文件夹,里面是 csv 文件。
Resolved .解决了。 It was pointed out to me that I need to join the directory and the file.有人向我指出,我需要加入目录和文件。 The following works for me now.以下内容现在对我有用。
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)))
Try the code below:试试下面的代码:
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.