使用"os"包在下载目录中搜索csv,然后用"pandas"自动读取它



我想让它向用户询问两个csv档案的名称,并让os.listdir()查找它们,一旦找到它们就用pandas打开它们,也许os.listdir()不是我真正需要的?

可以避免部分,问题是定义函数

from tkinter import filedialog
import pandas as pd
import os
def search_csv():
csv_file1 = entry1.get()
csv_file2 = entry2.get()
found_files = 0
for file in os.listdir("C:UsersChiscoDownloads"):
if file.endswith('.csv'):
if file == csv_file1:
df1 = pd.read_csv(file)
found_files += 1
elif file == csv_file2:
df2 = pd.read_csv(file)
found_files += 1
if found_files == 2:
break
if found_files < 2:
not_found = []
if found_files == 0:
not_found = [csv_file1, csv_file2]
elif csv_file1 not in locals():
not_found.append(csv_file1)
elif csv_file2 not in locals():
not_found.append(csv_file2)
print(f"{' and '.join(not_found)} not found.")
else:
print(df1)
print(df2)
root = tk.Tk()
root.title("CSV Search")
label1 = tk.Label(root, text="Enter first CSV File Name:")
label1.pack()
entry1 = tk.Entry(root)
entry1.pack()
label2 = tk.Label(root, text="Enter second CSV File Name:")
label2.pack()
entry2 = tk.Entry(root)
entry2.pack()
search_button = tk.Button(root, text="Search", command=search_csv)
search_button.pack()
root.mainloop()```

好了,我已经用这个新代码解决了这个问题:

import os
import pandas as pd
def search_csv():
csv_file1 = entry1.get()
csv_file2 = entry2.get()
found_files = 0
# Get the current user's "Downloads" directory
downloads_dir = os.path.expanduser("~/Downloads")
for root, dirs, files in os.walk(downloads_dir):
for file in files:
if file.endswith('.csv'):
if file == csv_file1:
file_path = os.path.join(root, file)
df1 = pd.read_csv(file_path)
found_files += 1
elif file == csv_file2:
file_path = os.path.join(root, file)
df2 = pd.read_csv(file_path)
found_files += 1
if found_files == 2:
break
if found_files < 2:
not_found = []
if found_files == 0:
not_found = [csv_file1, csv_file2]
elif csv_file1 not in locals():
not_found.append(csv_file1)
elif csv_file2 not in locals():
not_found.append(csv_file2)
print(f"{' and '.join(not_found)} not found in {downloads_dir}.")
else:
print('esto es viento:',df1)
print('esto es rumbo:',df2)
root = tk.Tk()
root.title("CSV Search")
label1 = tk.Label(root, text="Enter first CSV File Name:")
label1.pack()
entry1 = tk.Entry(root)
entry1.pack()
label2 = tk.Label(root, text="Enter second CSV File Name:")
label2.pack()
entry2 = tk.Entry(root)
entry2.pack()
search_button = tk.Button(root, text="Search", command=search_csv)
search_button.pack()
root.mainloop()```

相关内容

  • 没有找到相关文章

最新更新