0

I'm in the middle of a tutorial that has a seemingly simple task of reading a file but one of the tests to check the file seems to be failing.

employee_file = open("employees.txt", "r")
print(employee_file.readable())  # this returns "True" to the screen
print(employee_file.read())      # this reads out the file to screen, as is.
print(employee_file.readline())  # this returns a blank line
print(employee_file.readlines()) # this returns blank brackets.
employee_file.close()

My output window shows the following:

runfile('C:/Users/bsimmons/Documents/Python Scripts/reading_files_prac.py', wdir='C:/Users/bsimmons/Documents/Python Scripts')
True
Jim - Salesman
Dwight - Salesman
Pam - Receptionist
Michael - Manager
Oscar - Accountant
Bruce - Scientist
.

..
[]

I'm on a windows 10 laptop, I'm using Spyder 4.01, Python 3.7 and Chrome to run my video tutorial.

The txt file exists in the same directory as my script, and the text in the file looks like this:

Jim - Salesman
Dwight - Salesman
Pam - Receptionist
Michael - Manager
Oscar - Accountant
Bruce - Scientist

I've tested the file and Python says it's not empty. I've added blank lines after the last line, to no avail. I've listed the directory with test code and they show the file is there.

If I swap out

print(employee_file.readlines())

with

print(employee_file.readlines()[1])

I get list index out of range.

I'm at wits end because I feel that after a few hours of research, I can't seem to find the appropriate answer anywhere on how to resolve this seemingly simple test print. Or I have not recognized the fix when it slapped me in the face.

NAND
  • 663
  • 8
  • 22
BSimmons
  • 7
  • 2

2 Answers2

0

Once you read() the file you cannot read it any more. And also once you readline() you cannot read that line any more but you will read the line after it.

Reading a file is like a pointer that points to specific location in file, once you read that location the pointer will point to the next location until reaching the end of the file.

So once read() the file, it will be read, the pointer will point to the next location(the end of file), and then the file will be printed.

If you want to read the file again(make the pointer points to the beginning of the file again) you have to use

employee_file.seek(0)

according to this question .

NAND
  • 663
  • 8
  • 22
0
employee_file = open("employees.txt", "r")
print(employee_file.readable())
print(employee_file.read())
employee_file.seek(0) # Sets the reference point at the beginning of the file 
print(employee_file.readline())
print(employee_file.readlines())
employee_file.close()
Diego Magalhães
  • 1,704
  • 9
  • 14