簡體   English   中英

多行字符串連接並寫入文本文件

[英]multy line string concatenation and writing to a text file

我正在使用python的os庫來幫助我執行以下操作:

  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)

我有兩個問題。 首先,盡管沒有任何錯誤,但運行此命令后文本文件中實際存在的唯一內容是“列表:”。 另外我也不知道如何使用字符串連接來將每個文件名放在不同的行上。 我想念什么? 我怎樣才能做到這一點?

字符串在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.linesepos.linesep附加到您的串聯字符串中。 默認情況下,這是通過print完成的,因此,如果您希望外觀相同,則是個好主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM