Python - 如何在没有引号和空格的情况下将字符串写入文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20585559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:47:19  来源:igfitidea点击:

Python - how to write strings to file without quotes and spaces?

pythonstringio

提问by Andrius

Is it possible to write into file string without quotes and spaces (spaces for any type in list)?

是否可以在没有引号和空格(列表中任何类型的空格)的情况下写入文件字符串?

For example I have such list:

例如我有这样的清单:

['blabla', 10, 'something']

['blabla', 10, 'something']

How can I write into file so line in a file would become like:

如何写入文件,以便文件中的行变成:

blabla,10,something

blabla,10,something

Now every time I write it into file I get this:

现在每次我将它写入文件时,我都会得到这个:

'blabla', 10, 'something'

'blabla', 10, 'something'

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?

那么我需要用空符号替换'' '。也许有一些技巧,所以我不需要一直更换它?

采纳答案by Cyrille

This will work:

这将起作用:

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)

Output in file:

文件中的输出:

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.

这将导致对文件的每个后续写入都放在自己的行上。

回答by Cyrille

Did you try something like that ?

你有没有尝试过这样的事情?

yourlist = ['blabla', 10, 'something']
open('yourfile', 'a+').write(', '.join([str(i) for i in yourlist]) + '\n')

Where

在哪里

', '.join(...)take a list of strings and glue it with a string (', ')

', '.join(...)获取一个字符串列表并用一个字符串 ( ', ')将其粘合

and

[str(i) for i in yourList]converts your list into a list of string (in order to handle numbers)

[str(i) for i in yourList]将您的列表转换为字符串列表(以便处理数字)

回答by Jon..

Initialise an empty string j
for all item the the list,concatenate to j which create no space in for loop,
printing str(j) will remove the Quotes


为列表中的所有项目初始化一个空字符串 j ,连接到 j,在 for 循环中不创建空间,
打印 str(j) 将删除引号

  j=''
  for item in list:
       j = j + str(item)
  print str(j)