Python Reading A Tab Separated File Using Delimiter
Solution 1:
I would also suggest to use the csv module. It is easy to use and fits best if you want to read in table like structures stored in a CSV like format (tab/space/something else delimited).
The module documentation gives good examples where the simplest usage is stated to be:
import csv
withopen('/tmp/data.txt', 'r') as f:
reader = csv.reader(f)
for row in reader:
print row
Every row is a list which is very usefull if you want to do index based manipulations.
If you want to change the delimiter there is a keyword for this but I am often fine with the predefined dialects which can also be defined via a keyword.
import csv
withopen('/tmp/data.txt', 'r') as f:
reader = csv.reader(f, dialect='excel', delimiter='\t')
for row in reader:
print row
I am not sure if this will fix your problems but the use of elaborated modules will ensure you that something is wrong with your file and not your code if the error will remain.
Solution 2:
It should work but it is better to use 'with':
withopen('/tmp/data.txt') as f:
for l in f:
print l.strip().split("\t")
if it doesn't then probably your file doesn't have the required format.
Post a Comment for "Python Reading A Tab Separated File Using Delimiter"