Code_E
Code_E

Reputation: 13

Why does reading a .txt file with Python results in a blank line in the console?

I am at a part of a tutorial where I'm reading a .txt file. I followed the instructions key for key, but my console log is returning a blank line.

Does anyone know what could be off?

employee_file = open('employees.txt', 'r')

print(employee_file.readline())

employee_file.close()

Upvotes: 1

Views: 1596

Answers (4)

The Guy
The Guy

Reputation: 421

Use seek() function of file object.

This sets the file's current position at the offset, may be the cursor in your file is at last position, because of this you are getting nothing.

update your code:

employee_file = open('employees.txt', 'r')
employee_file.seek(0)  # Sets cursor in your file at absolute position (At beginning)

print(employee_file.readline())

This should work.

Upvotes: 0

Gino Mempin
Gino Mempin

Reputation: 29549

It is possible that in the same console session, you already opened and read the file but forgot to close it. Then you re-ran the same readline or readlines() which would return empty because the file pointer is already at the end of the file.

$ cat employees.txt
Jim-Sales
111
222

$ python3.7
Python 3.7.2 (default, Mar  8 2019, 19:01:13) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> employee_file = open('employees.txt', 'r')
>>> print(employee_file.readline())
Jim-Sales

>>> print(employee_file.readlines())
['111\n', '222\n']
>>> 
>>> 
>>> 
>>> print(employee_file.readline())

>>> print(employee_file.readlines())
[]

That's why the recommended practice is to always wrap it in a with statement:

>>> with open("employees.txt", "r") as employee_file:
...      print(employee_file.readlines())
... 
['Jim-Sales\n', '111\n', '222\n']
>>> with open("employees.txt", "r") as employee_file:
...      print(employee_file.readlines())
... 
['Jim-Sales\n', '111\n', '222\n']

Upvotes: 0

Kevin Omar
Kevin Omar

Reputation: 137

First of all make sure that you work in the same path where the file is, Use this: print(os.getcwd()) Second make sure that file is not empty and save it. Third Use Code written by @bashBedlam and it should work.

I hope this help you.

Upvotes: 0

bashBedlam
bashBedlam

Reputation: 1500

Try it like this:

with open ('employees.txt') as file :
    for line in file :
        print (line)

Upvotes: 3

Related Questions