简体   繁体   English

在python中读取包含列表和逗号分隔的文件

[英]read a file contains list and comma separation in python

I have a file(.txt) which contains: [0 1,1 1,3 2,4 1] 我有一个文件(.txt),其中包含: [0 1,1 1,3 2,4 1]

I want to read the file in this way: 我想以这种方式读取文件:

0 1 /n
1 1 /n
3 2 /n
4 1 /n

I have problem how to eliminate brackets and separate each line by comma. 我有问题如何消除方括号并以逗号分隔每行。 Thanks for your suggestions :) 感谢您的建议:)

>>> s = "[0 1,1 1,3 2,4 1]"
>>> print '\n'.join(s[1:-1].split(','))
0 1
1 1
3 2
4 1

A different method that will also work if the brackets are not the first and the last character: 如果方括号不是第一个和最后一个字符,也可以使用另一种方法:

print s[s.index("[")+1:s.index("]")].replace(",", "\n")

If the brackets always are the ifrst and the last character of the string, you can simplify this to 如果方括号始终字符串的第一个字符和最后一个字符,则可以将其简化为

print s[1:-1].replace(",", "\n")

Simple snippet: 简单代码段:

with open("file.txt", "r") as _f:
    myfile = _f.readlines()

myline = myfile[0]

print '\n'.join(myline[1:-1].split(','))

If you have several similar lines on your file, on can iterate with a for statement on 'myfile'. 如果文件上有几行相似的行,则可以在“ myfile”上使用for语句进行迭代。

for line in myfile:
    print '\n'.join(line[1:-1].split(','))

Note, if you are sure that brackets are on beginning and end of the line, you can use : 请注意,如果确定方括号在行的开头和结尾,则可以使用:

print "\n".join(line.strip('[]').split(','))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM