【问题标题】:How to iterate through subfolders and convert files into csv while saving them in that subfolder如何遍历子文件夹并将文件转换为csv,同时将它们保存在该子文件夹中
【发布时间】:2022-06-20 20:59:26
【问题描述】:

我有一个文件夹和子目录,其中包含 txt 文件。我想将每个 txt 文件转换为 csv 并将文件与 txt 文件同名但以 csv 格式保存。例如,我有一个名为 A 的文件夹,而 A 有

  • 子文件夹 B(B 有子文件夹 C、D 等)。每个子文件夹中都有一个文件,名称不同,例如 test1.txt、test112.json 等。
  • 子文件夹 E(E 有 F、K 等子文件夹)。每个子文件夹里面都有一个不同名字的文件,比如子文件夹F里面有testF.txt、testFgf.json等,子文件夹K里面有testKk.txt。

我想将每个 .txt 文件转换为每个子文件夹的 .csv 文件,并具有与以下相同的文件名:

  • 子文件夹 B(B 有子文件夹 C、D 等)。每个子文件夹中都有一个名称不同的文件,例如 test1.txt、test1.json、test1.csv
  • 子文件夹 E(E 有 F、K 等子文件夹)。每个子文件夹中都有一个不同名称的文件,例如子文件夹 F 有 testF.txt、testF.json、testF.csv,子文件夹 K 有 testKk.txt、testKk.csv。 我试过了:
root="C:/user/main_folder/A/"
for path, subdirs, files in os.walk(root):
    for name in files:
        filepath = root + os.sep + name
         if filepath.endswith(".txt"):
            print(os.path.join(path, name))
            file=task_info
            task_info.to_csv(path.join(filepath, file_name), index=False)

在这里,我可以从每个子文件夹中获取正确的文件路径,但我无法将它们转换为 csv 并以正确的名称将它们保存在正确的文件夹中。 任何帮助将不胜感激。

【问题讨论】:

  • 您的尝试发生了什么?它会产生任何错误吗?如果是这样,请考虑在问题中提出该错误。在代码的最后一行中,您已将 os. 从应该是 os.path.join() 中删除。

标签: python csv path iteration subdirectory


【解决方案1】:

你可以使用递归

root="C:/user/main_folder/A"

def explore_and_execute(initial_path):
    for item in os.listdir(initial_path):
        item_fullpath = initial_path+"/"+item
        if os.path.isdir(item):
            explore_and_execute(item_fullpath)
        if os.path.isfile(item):
            if item.endswith(".txt"):
                os.rename(item_fullpath, item_fullpath[:-4]+".csv")

explore_and_execute(root)    

在这里你将循环直到目录分支结束

【讨论】:

  • os.walk() 内置了递归。为什么要在这里推出自己的产品?
  • 这个有效。为什么不?客观一点
  • 谢谢,但我想问一下我是否要编辑文件然后保存然后我该怎么做?
【解决方案2】:

您需要使用的文件路径:

def store(data, root, name):
    name = name.split('.')[0] # To get just the name and remove the file extension
    with open(root+os.sep+name+'.csv'. 'w') as f2:
       f2.write(data)  

root="C:/user/main_folder/A/"
for path, subdirs, files in os.walk(root):
    for name in files:
        filepath = root + os.sep + name
            if filepath.endswith(".txt"):
                with open(filepath, 'r') as file:
                    # Here you can do anything you want to do with the file if you want to modify it somehow and if it is a .txt with .csv format, do nothing.
                    store(file, root, name)

【讨论】:

  • 谢谢。但是,您的代码不会通过所有子目录来获取所有需要的文件。其次,我认为你的 def store 函数在 open() 行中有一个错误。总的来说,当我尝试这段代码时,它给出了一个错误 FileNotFoundError: [Errno 2] No such file or directory: 'filepath'.
  • 是的,错误是我使用文件路径作为字符串,而不是使用存储在变量文件路径中的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-08
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多