是否可以写入没有引号和空格的文件字符串(列表中任何类型的空格)?
例如,我有这样的清单:
['blabla', 10, 'something']
如何写入文件,以便文件中的行变为:
blabla,10,something
现在,每当我将其写入文件时,我都会得到:
'blabla', 10, 'something'
那么我需要替换'并' '使用空符号.也许有一些技巧,所以我不需要一直更换它?
这将有效:
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)
Run Code Online (Sandbox Code Playgroud)
文件输出:
blabla,10,something
Run Code Online (Sandbox Code Playgroud)
但请注意,上面的代码可以简化:
lst = ['blabla', 10, 'something']
with open("/path/to/file", "a+") as myfile:
myfile.write(",".join(map(str, lst)))
Run Code Online (Sandbox Code Playgroud)
此外,您可能希望在写入文件的行末尾添加换行符:
myfile.write(",".join(map(str, lst))+"\n")
Run Code Online (Sandbox Code Playgroud)
这将导致对文件的每个后续写入都放在它自己的行上.
| 归档时间: |
|
| 查看次数: |
18169 次 |
| 最近记录: |