0

As part of a bigger project, I would simply like to make sure that a file can be opened and Python can read and use it. So after I opened up the txt file, I said:

data = txtfile.read()

first_line = data.split('\n',1)[2]

print(first_line)

I also tried

print(f1.readline())

where f1 is the txt file. This, again, did nothing. I am using the spyder IDE, and it just says running file, and doesn't print anything. Is it because my file is too large? It is 4.6 gigs.

Does anyone have any idea what's going on?

1408786user
  • 1,868
  • 1
  • 21
  • 39
Goku241
  • 81
  • 5
  • print(f1.readline()) should work, are you sure the file does not contain everything in a single line? Or at least a very long first line? – 1408786user Aug 30 '17 at 06:44
  • If those lines are empty (except for whitespace characters - spaces, tabs, newlines etc), then obviously printing them won't display much... – bruno desthuilliers Aug 30 '17 at 08:46

2 Answers2

0

and it just says running file, and doesn't print anything. Is it because my file is too large? It is 4.6 gigs.

Yes.

data = txtfile.read()

This function is going to read the entire file. Since you stated that the file is 4.6GB, it is going to take time to load the entire file and then split the by newline character.

See this: Read large text files in Python

I don't know your context of use, so, if you can process line by line, it would be simpler. Or even chunks would make it simpler than reading the entire file.

SajidSalim
  • 359
  • 6
  • 19
-1
first_line =  open('myfile.txt', 'r').readline()
Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188