Python - 如何在没有引号和空格的情况下将字符串写入文件? [英] Python - how to write strings to file without quotes and spaces?
问题描述
是否可以写入没有引号和空格的文件字符串(列表中任何类型的空格)?
Is it possible to write into file string without quotes and spaces (spaces for any type in list)?
例如我有这样的列表:
['blabla',10,'something']
如何写入文件,以便文件中的行变为:
How can I write into file so line in a file would become like:
blabla,10,某事
现在每次把它写入文件我都会得到:
Now every time I write it into file I get this:
'blabla', 10,'某事'
那么我需要更换'
和''
带空符号。也许有一些技巧,所以我不需要一直更换它?
So then I need to replace '
and ' '
with empty symbol. Maybe there is some trick, so I shouldn't need to replace it all the time?
推荐答案
这将有效:
lst = ['blabla', 10, 'something']
# Open the file with a context manager
with open("/path/to/file", "a+") as myfile:
# Convert all of the items in lst to strings (for str.join)
lst = map(str, lst)
# Join the items together with commas
line = ",".join(lst)
# Write to the file
myfile.write(line)
文件输出:
blabla,10,something
但是请注意以上代码可以简化:
Note however that the above code can be simplified:
lst = ['blabla', 10, 'something']
with open("/path/to/file", "a+") as myfile:
myfile.write(",".join(map(str, lst)))
此外,您可能想要添加换行符你写入文件的行的结尾:
Also, you may want to add a newline to the end of the line you write to the file:
myfile.write(",".join(map(str, lst))+"\n")
这将导致文件的每个后续写入都被放置在它自己的路线。
This will cause each subsequent write to the file to be placed on its own line.
这篇关于Python - 如何在没有引号和空格的情况下将字符串写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!