我目前正在學習 - 我不了解很多關于 python/pandas 的細節。因此,可能有一個簡單的解決方法。
目前我正在嘗試做的是在選擇目錄中列出 txt 檔案,然后能夠通過數字/索引選擇它們。然后將其作為資料框讀取,以便我對其進行資料分析。
例如
- 用戶輸入目錄 -> 代碼列出檔案夾/目錄中的檔案
0.text.txt
1.text2.txt
- 用戶應該能夠按索引/編號選擇檔案
Select file number:
0
- 并將所選檔案作為資料框傳遞。
這是我到目前為止所嘗試的:
#user inputs directory
input_dir = input(r'Enter location of INPUT folder: ')
#list filenames and select file by number selection.
filelist = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
for cnt in range(len(filelist)):
filename = filelist[cnt]
print (cnt, filename)
choice = input("select file number: ")
# open the file based on the key input by user
df = pd.read_csv(filelist[int(choice)])
輸出:
0 test.txt
1 test2.txt
但是在選擇索引后我不斷收到相應的錯誤:
handle = open(
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
uj5u.com熱心網友回復:
df = pd.read_csv(f"{input_dir}/{filelist[int(choice)]}")
uj5u.com熱心網友回復:
您需要提供檔案的路徑
另一種提供方法是使用os.path.join(input_dir, f)您在filelist = ...
所以會是這樣
# open the file based on the key input by user
df = pd.read_csv(os.path.join(input_dir, filelist[int(choice)]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/525433.html
標籤:Python熊猫数据框
上一篇:獲取列中特定單詞之后的第一個單詞
