【问题标题】:Python: How do I create a code that loops through csv files in a folderPython:如何创建循环遍历文件夹中的 csv 文件的代码
【发布时间】:2020-06-28 00:36:12
【问题描述】:
我尝试创建一个 python 代码,该代码将转到我在笔记本电脑上创建的包含 csv 文件的文件夹,然后循环遍历所有 csv 文件,然后将它们全部放入用户指定的文件夹中。到目前为止,这就是我所得到的,我需要帮助来完成这段代码。我尝试运行此代码,但没有任何反应。如果有人有更简单的方法来创建此代码,那也很棒。
import pandas as pd
import glob
path = r"C:\Users\Documents\Practicefolder1\*.csv"
for Tname in glob.glob(path):
print(Tname)
【问题讨论】:
标签:
python
csv
for-loop
directory
export-to-csv
【解决方案1】:
重命名文件,使文件路径反映适当的目录。
import pandas as pd
import glob
import os
# The folder that the files will be moved to
user_specified_folder = input('Please specify the folder to put the files in')
path = r'C:\Users\Documents\Practicefolder1\*.csv'
for Tname in glob.glob(path):
# get the name of the file itself
file_name = os.path.basename(Tname)
# get a new file name for the new path
new_file_name = os.path.join(user_specified_folder,file_name)
# rename the file so that it is in the appropriate directory
os.rename(Tname, new_file_name);