我使用python的OS庫,幫助我做到以下幾點:MULTY行字符串連接和寫入到一個文本文件
- 詢問用戶的路徑。
- 打印包含在其中的所有目錄和文件。
- 將信息保存在文本文件中。
這是我的代碼:
import os
text = 'List:'
def print_tree(dir_path,text1):
for name in os.listdir(dir_path):
full_path = os.path.join(dir_path, name)
x = name.find('.')
if x!= -1:
print name #replace with full path if needed
text1 = text1 + name
else:
print '------------------------------------'
text1 = text1 + '------------------------------------'
print name
text1 = text1 + name
if os.path.isdir(full_path):
os.path.split(name)
print '------------------------------------'
text1 = text1 + '------------------------------------'
print_tree(full_path,text1)
path = raw_input('give me a dir path')
print_tree(path,text)
myfile = open('text.txt','w')
myfile.write(text)
我有兩個問題。首先,雖然沒有任何錯誤,但運行此文件後,文本文件中實際存在的唯一內容是「List:」。此外,我不知道如何使用字符串連接,以便將每個文件名稱放在不同的行上。我錯過了什麼?我怎樣才能做到這一點?
添加「\ n」將文本放入新行。 – furas
@furas說'\ n列表:'?這是正確的嗎? –
「一行」+「\ n」+「新行」+「\ n」+「另一行」。或「一行\ n新行\ nanother行」 – furas