gpt4 book ai didi

python - 多行字符串连接和写入文本文件

转载 作者:太空宇宙 更新时间:2023-11-04 10:18:18 25 4
gpt4 key购买 nike

我正在使用 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.linesep 附加到您的串联字符串中。这是默认情况下由 print 完成的,所以如果您希望事情看起来一样,这是个好主意。

关于python - 多行字符串连接和写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33959455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com