简体   繁体   中英

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]

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'.

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(','))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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