我想用python中的兩個不同的文件夾(一個文本文件)寫一個列表;但是,當我運行我的程序時,只有第二個文件路徑追加到列表中,並出現在我的文本文件中。如何追加我的列表以便兩個文件夾中的文件都顯示出來?我想我的代碼在第一步之後清空列表。我想保持兩個文件夾分開,不想僅僅爲了列表而將它們合併。從python中的兩個不同的文件夾創建文本文件
import os
from os import listdir
from os.path import isfile, join
root = r'C:\GEO\Images\data\data_2008\ims_data_2008'
mylist = [ ]
for path, subdirs, files in os.walk(root):
for name in files:
mylist.append(os.path.join(path, name))
roottwo = r'C:\GEO\Images\data\data_2009\ims_data_2009'
mylist = [ ]
for path, subdirs, files in os.walk(roottwo):
for name in files:
mylist.append(os.path.join(path, name))
txt = open(r'C:\GEO6973\FinalExam\YoungResults\ims_data_list.txt', 'w')
txt.write('dir' + ',' + 'file' + '\n')
for item in mylist:
list = mylist.pop(0)
dir, filename = os.path.basename(os.path.dirname(list)), os.path.basename(list)
txt.write(dir + ',' + filename + '\n')
with open(r'C:\GEO6973\FinalExam\YoungResults\ims_data_list.txt', 'r') as f:
read_data = f.read()
如果我在roottwo後刪除themylist,只有根文件寫入我的列表。 –
刪除mylist的重新定義後,不應該發生這種情況。第一次聲明後,您只能附加項目。如果在打開輸出文件之前打印mylist,則應該有兩個文件夾的內容。 – ODiogoSilva
刪除重新定義不起作用。我認爲這與我的mylist.pop(0)聲明有關。 –