【发布时间】:2020-03-22 19:51:01
【问题描述】:
我在 python 3.7 上创建了一个循环,该循环转到 20 个目录并将 .txt 文件的副本创建为 .csv 文件。
编译后,我在随机目录上遇到错误,而在其他目录上,循环执行我想要的操作
代码是(我使用微软):
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 目录都是邻居,并且都在“所有数据”目录中
我使用 os.path.join 解决了这个问题,但没有成功 我意识到微软的反斜杠/正斜杠问题
如果我将删除失败消息“找不到 DDX 文件!”我会收到错误 FileNotFoundError: [Errno 2] 文件“文件路径”不存在
【问题讨论】:
-
我认为问题在于上述文件夹中没有文件:DD2.txt、DD3.txt、DD5.txt
-
但是有一个文件,我明明查过了
-
奇怪!不用担心。你能粘贴“os.listdir(os.path.join(source_folder, mid_folder1, mid_folder2))”的输出吗?
-
FileNotFoundError: [WinError 3] 系统找不到指定的路径:'All Data\\DD20\\MindWare'
-
我对我的答案进行了编辑。你能给我它的输出吗?谢谢
标签: python openfiledialog