Reputation: 79
I have a text file (.txt) with different lines of words For example:
1,2,3,4,5
11,12,13,14,15
How can I use the file.read().split()
command to just get the 2nd column...so 2 and 12 for example of the text?
Upvotes: 1
Views: 57
Reputation: 37003
First you have to split the file into lines (easily done simply by iterating over it), than you have to extract the 2nd column from each line.
Simple example:
with open("myfile.txt") as myfile:
for line in myfile:
print(line.split(",")[1]) # indexing starts at 0
To accumulate a list of the values:
with open("myfile.txt") as myfile:
mylist = [line.split(",")[1] for line in myfile]
Upvotes: 2
Reputation: 41987
Assuming no spaces around ,
:
with open('file.txt') as f:
for line in f:
print(line.split(',')[1])
If there could be whitespaces, use re.split()
:
with open('file.txt') as f:
for line in f:
print(re.split(r'\s?,\s?', line)[1])
Upvotes: 4