如何让Python请求目录,读取目录中的每个文件名,并将该文件名(不带.csv)分别放在同一个文件中



我对Python很陌生,我有几百个文件夹,其中有数千个文件,每个文件都包含时间序列数据。每个文件都有一个匿名的唯一文件名,后面跟着下划线和每个文件的文件号(0到文件夹中有多少文件(;18667_0.csv、18667_1.csv和18667_3.csv";我需要运行一个for循环,它将使用这个唯一的文件名";18667〃;并将其放在我为同一csv文件选择的任何单元格中(我使用excel读取csv(。因此,如果我在文件夹中有300个文件,所有文件都将具有唯一的";18667〃;我只想把这个号码放在文件里。我有dir请求的部分代码,但我没有成功地组合正确的读/写语句来实现这项任务。这是我的

import tkinter as tk
import pandas as pd
from tkinter import filedialog
from os import listdir
def find_csv_filenames( path_to_dir, suffix=".csv" ):
filenames = listdir(path_to_dir)
return [ filename for filename in filenames if filename.endswith( suffix ) ]
root = tk.Tk()
root.withdraw()
folder_path = filedialog.askdirectory()
all_csvfiles = find_csv_filenames(folder_path, suffix= ".csv")
for filename in all_csvfiles:
print(filename)
a = filename
with open(a, 'w', newline="") as file:
csvwriter = csv.writer(file) # 2. create a csvwriter object
csvwriter.writerow(a)

最终完成了这项工作。

import tkinter as tk
from tkinter import filedialog
from os import listdir

# Listing all csv in folder
def find_csv_filenames(path_to_dir, suffix=".csv"):
filenames = listdir(path_to_dir)  #returns all filenames
return [filename for filename in filenames if filename.endswith(suffix)] 
#returns only csv filenames in a list []
#This is GUI for asking to select folder
root = tk.Tk()
root.withdraw()
folder_path = filedialog.askdirectory() #Returns the folder you selected
all_csvfiles = find_csv_filenames(folder_path, suffix=".csv")  #lists filenames
print(folder_path)
for filename in all_csvfiles:  #begin loop thru all csv files
print(filename)
# a = filename
InsertedName = filename[:-4]  #removes last 4 chars from filename
print(InsertedName)
tempfile = open(folder_path + "/temp.csv", "w") # creates a tempfile for 
writing(w) in the same dir
tempfile.write(InsertedName+"n")  #will write filename to temp and instruct 
for newline
sourcefile = open(folder_path + "/" + filename, "r") #creates a sourcefile 
for reading original
for line in sourcefile: #begins loop for writing original data to tempfile
tempfile.write(line) #writes the data
sourcefile.close()  #closes sourcefile
Finalfile = open(folder_path + "/" + filename, "w")  #creating finalfile to 
overwrite existing file in dir
tempfile.close()  #closes tempfile to return pointer to the top of file
tempfile = open(folder_path + "/temp.csv", "r") #opens tempfile to write 
tempfile data to finalfile
for line in tempfile: #loops the lines to write
Finalfile.write(line)
tempfile.close()
Finalfile.close()

最新更新