-1

I am reading a .txt file in python. It contains five columns of numbers. I have tried to find the number of elements using

numcols = len(linesX[0])

Unfortunately, since python reads the .txt as a list of strings

f = open('XdataTXT.txt','r')
linesX=f.readlines()

The output is 81 instead of 5. I have tried to implement the solution offered in this thread, but since they are dealing with a .csv instead of a .txt I cannot replicate the results. Can someone help me?

In the attached image you can see how my original data looks.xt

1
  • Please don’t share information as images unless absolutely necessary, which isn’t the case here. Can you share a minimal reproducible example? It isn’t clear to me what the issue is. Are you just asking how to read this whitespace-delimited data? If so, there are plenty of resources on the subject. Commented Jan 29, 2020 at 18:04

1 Answer 1

1

The csv library does not depend on the filename suffix. It's the data in the file that it deals with. Therefore you can definitely still use the csv library for this.

import csv

with open('XdataTXT.txt','r') as f:
    numcols = len(next(csv.reader(f, delimiter=' ')))

Or if you don't want to use the library just use str.split:

with open('XdataTXT.txt','r') as f:
    numcols = len(f.readline().split())
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, but I am afraid that numcols is 1 instead of 5 if I write with open('XdataTXT.txt','r') as f: numcols = len(next(csv.reader(f))) f.close()
You need to set the delimiter to a space as the dafault is a comma. See my edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.