2015-11-27 22 views
1

我使用python的OS庫,幫助我做到以下幾點:MULTY行字符串連接和寫入到一個文本文件

  1. 詢問用戶的路徑。
  2. 打印包含在其中的所有目錄和文件。
  3. 將信息保存在文本文件中。

這是我的代碼:

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:」。此外,我不知道如何使用字符串連接,以便將每個文件名稱放在不同的行上。我錯過了什麼?我怎樣才能做到這一點?

+0

添加「\ n」將文本放入新行。 – furas

+0

@furas說'\ n列表:'?這是正確的嗎? –

+1

「一行」+「\ n」+「新行」+「\ n」+「另一行」。或「一行\ n新行\ nanother行」 – furas

回答

4

字符串在Python中是不可變的,而對它們的+=運算符只是一種幻覺。您可以在函數中連接所有您想要的字符串,但除非您將其返回,否則函數外部的字符串將不會更改:text1 = text1 + 'blah'將創建一個新字符串,並將其引用分配給text1。函數外部的字符串沒有改變。解決的辦法是建立一個字符串,然後返回它:

import os 
text = 'List:' + os.linesep 
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 + os.linesep 
     else: 
      print '------------------------------------' 
      text1 = text1 + '------------------------------------' + os.linesep 
      print name 
      text1 = text1 + name + os.linesep 

     if os.path.isdir(full_path): 
      os.path.split(name) 
      print '------------------------------------' 
      text1 = text1 + '------------------------------------' + os.linesep 
      text1 = print_tree(full_path,text1) 
    return text1 

path = raw_input('give me a dir path') 
text = print_tree(path,text) 
myfile = open('text.txt','w') 
myfile.write(text) 

我還需要追加os.linesep你的串聯字符串的自由。這是由print默認完成的,所以如果你想讓事情看起來一樣,這是一個好主意。

+0

它的工作!感謝您的幫助。我不能相信我忘了回來:/ –

+2

很高興幫助。請在這種情況下選擇此答案。 –