[英]multy line string concatenation and writing to a text file
I am using the os library of python to help me do the following: 我正在使用python的os库来帮助我执行以下操作:
this is my code: 这是我的代码:
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)
I have two problems. 我有两个问题。 First, although there's no error whatsoever, the only thing that actually exists in the text file after running this is 'List:'.
首先,尽管没有任何错误,但运行此命令后文本文件中实际存在的唯一内容是“列表:”。 Also i don't know how to use string concatenation in order to put each file name on a different line.
另外我也不知道如何使用字符串连接来将每个文件名放在不同的行上。 What am i missing?
我想念什么? How can i accomplish this?
我怎样才能做到这一点?
Strings are immutable in Python, and the +=
operator on them is just an illusion. 字符串在Python中是不可变的,它们上的
+=
运算符只是一种幻想。 You can concatenate a string all you want in the function, but unless you return it, the string outside the function will not change: text1 = text1 + 'blah'
creates a new string, and assigns its reference to text1
. 您可以在函数中连接所有想要的字符串,但是除非返回它,否则函数外部的字符串将不会更改:
text1 = text1 + 'blah'
创建一个新字符串,并将其引用分配给text1
。 The string outside the function has not changed. 函数外部的字符串未更改。 The solution is to build up a string and then return it:
解决方案是建立一个字符串,然后返回它:
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)
I have also take the liberty of appending os.linesep
to your concatenated strings. 我还可以
os.linesep
将os.linesep
附加到您的串联字符串中。 This is done by default by print
, so if you want things to look the same, it is a good idea. 默认情况下,这是通过
print
完成的,因此,如果您希望外观相同,则是个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.