Opening A Space(?) Delimited Text File In Python 2.7?
I have what I think is a space delimited text file that I would like to open and copy some of the data to lists (Python 2.7). This is a snippet of the data file: 0.000000
Solution 1:
One alternative is to take advantage of the built-in str.split()
:
a, b, c, d, e = zip(*((map(float, line.split()) for line in open('data_file.txt'))))
Solution 2:
The problem is the multiple spaces between fields (columns).
CSV stands for comma-separated values. Imagine for a second that you are using commas instead of spaces. Line 1 in your file would then look like:
,,,,0.000000,,,,,,,11.00,,,,,,737.09,,,,,,,1.00,,,,,1116.00
So, the CSV reader sees more than 5 fields (columns) in that row.
You have two options:
- Switch to using single space separators
- Use a simple split() to deal with multiple whitespace:
:
listb = []
listd = []
with open('text', 'r') as file:
for row in file:
a, b, c, d, e = row.split()
listb.append(int(b))
listd.append(int(d))
P.S: Once this part is working, you will run into a problem calling int() on strings like "11.00" which aren't really integers. So I recommend using something like:
int(float(b))
Solution 3:
f=open("input.txt",'r')
x=f.readlines()
list1=[]
list2=[]
import re
for line in x:
pattern=re.compile(r"(\d+)(?=\.)")
li=pattern.findall(line)
list1.append(li[1])
list2.append(li[3])
You can use this if you only want to capture integers
and not floats
.
Solution 4:
You can find all values you need, using regexp
import re
list_b = []
list_d = []
with open('C://data_file.txt', 'r') as f:
for line in f:
list_line = re.findall(r"[\d.\d+']+", line)
list_b.append(float(list_line[1])) #appends second column
list_d.append(float(list_line[3])) #appends fourth column
print list_b
print list_d
Post a Comment for "Opening A Space(?) Delimited Text File In Python 2.7?"