随机获取FileNotFoundError:[Erno 2]文件不存在



我在python 3.7上创建了一个循环,该循环指向20个目录,并将.txt文件的副本创建为.csv文件。

编译后,我在随机目录上得到了错误,而在其他目录上,循环会做我想要的

代码是(im使用Microsoft(:

import pandas as pd
from datetime import datetime
from os import path
import os
source_folder = "All Data"
for i in range(1, 21):
mid_folder1 = "DD" + str(i)
mid_folder2 = "MindWare"
file_name = "DD" + str(i) + '.txt'
full_path = os.path.join(source_folder, mid_folder1, mid_folder2, file_name)
if path.isfile(full_path):
df = pd.read_csv(full_path, sep="t")
df.to_csv(os.path.join(source_folder, mid_folder1, mid_folder2, "DD" + str(i) + '.txt'))
print("DD" + str(i) + " is successfully CSVed")
else:
print("Cannot find DD" + str(i) + " file!")

我收到的输出是:

DD1 is successfully CSVed
Cannot find DD2 file!
Cannot find DD3 file!
DD4 is successfully CSVed
Cannot find DD5 file!
Cannot find DD6 file!
DD7 is successfully CSVed
Cannot find DD8 file!
Cannot find DD9 file!
Cannot find DD10 file!
Cannot find DD11 file!
DD12 is successfully CSVed
DD13 is successfully CSVed
Cannot find DD14 file!
Cannot find DD15 file!
Cannot find DD16 file!
Cannot find DD17 file!
Cannot find DD18 file!
Cannot find DD19 file!
Cannot find DD20 file!

这很奇怪,因为所有的DD1-DD20目录都是邻居,并且所有的都在"all data"目录中

我使用os.path.join解决了这个问题,但没有成功我意识到微软反斜杠/反斜杠问题

如果我将删除失败消息"找不到DDX文件!"我将得到错误FileNotFoundError:[Erno 2]文件"文件路径"不存在

请尝试此代码:

import pandas as pd
from datetime import datetime
from os import path
import os
source_folder = "All Data"
for i in range(1, 21):
mid_folder1 = "DD" + str(i)
mid_folder2 = "MindWare"
file_name = "DD" + str(i) + '.txt'
full_path = os.path.join(source_folder, mid_folder1, mid_folder2, file_name)
if path.exists(full_path):  # check is file exists
df = pd.read_csv(full_path, sep="t")
df.to_csv(os.path.join(source_folder, mid_folder1, mid_folder2, "DD" + str(i) + '.txt'))
print("DD" + str(i) + " is successfully CSVed")
else:
print("File: " + full_path + " does not exist!")

它基本上检查文件是否存在。与您的略有不同

干杯!

编辑:要调试,您可以尝试以下操作吗:

import os
source_folder = "All Data"
for path, subdirs, files in os.walk(source_folder):
for name in files:
print(os.path.join(path, name))

这是为了理解的文件结构

最新更新