Skip to Content

Advertisement

You (Level 0)
0% Complete
Last Badge Earned
None

Many times, a programmer finds a reason to read content from a file. It could be that we want to read from a text file, such as a log file, or an XML file for some serious data retrieval. Sometimes, it is a massive task to figure out how to do it exactly. No worries, Python is smooth like always and makes reading files a piece of cake. There are primarily 2 ways in which Python likes to read. To keep things simple, we are just going to read from text files, feel free to explore XML on your own later. XML is a pretty cool markup, but as you get deeper, it is kind of a headache. Enough of my tangents, to the coding board:

Opening a File in Python

test.txt I am a test file.
Maybe someday, he will promote me to a real file.
Man, I long to be a real file
and hang out with all my new real file friends.
Example f = open("test.txt", "r") #opens file with name of "test.txt"

This is pretty simple to explain. We have our awesome little test.txt file filled with some random text. Now, in the example we have our code. Just like you click a file to open it, Python needs to know what file to open. So, we use the open method to tell Python what we want to open and to go ahead and open (make a connection to) it. The "r" just tells Python that we want to read (it is "w" when we want to write to a file). And, of course, we set this new connection to a variable so we can use it later. However, we have only opened a file, which is not all that exciting. Let's try reading from the file.

Python File Reading Methods

  • file.read(n) - This method reads n number of characters from the file, or if n is blank it reads the entire file.
  • file.readline(n) - This method reads an entire line from the text file.
Example f = open("test.txt","r") #opens file with name of "test.txt"
print(f.read(1))
print(f.read())
Result I
 am a test file.
Maybe someday, he will promote me to a real file.
Man, I long to be a real file
and hang out with all my new real file friends.

Woot woot! So, this might be a little confusing. First, we open the file like expected. Next, we use the read(1), and notice that we provided an argument of 1, which just means we want to read the next character. So, Python prints out "I" for us because that is the first character in the test.txt file. What happens next is a little funky. We tell Python to read the entire file with read() because we did not provide any arguments. But, it doesn't include that "I" that we just read!? It is because Python just picks up where it left off. So, if Python already read "I", it will start reading from the next character. The reason for this is so you can cycle through a file without have to skip so many characters each time you want to read a new character. It's complicated, I know, but think of reading like a one way process. Python is lazy, it doesn't want to go back and reread contents. Let's take this one step further with reading lines.

Example f = open("test.txt","r") #opens file with name of "test.txt"
print(f.readline())
print(f.readline())
Result I am a test file.
Maybe someday, he will promote me to a real file.

Ha! This time we were prepared for Python's trickery. Since we just used the readline() method twice, we knew that we would get first 2 lines because of Python's reading process. Of course, we also knew that readline() reads only a line because of it's simple syntax. Alright, one last important, complicated, and awesome thing about Python's reading abilities.

Example f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
print(myList)
Result ['I am a test file.\n', 'Maybe someday, he will promote me to a real file.\n', 'Man, I long to be a real file\n', 'and hang out with all my new real file friends.']

What!? Python just blew our minds! First, don't freak out with the \n. It is just a newline character, since those lines are on a different file, Python wants to keep that format (you can always strip them out later).We open the file like normal, and we create a list, which we have mastered by now. Then, we break the file into lines in our for loop using the in keyword. Python is magically smart enough to understand that it should break files into lines. Next, as we are looping through each line of the file we use myList.append(line) to add each line to our myList list. Finally, when we print it out, Python shows us its glory. It broke each line of the file into a string, which we can manipulate to do whatever we want.

Wait! Don't forget to close the file!

Example f = open("test.txt","r") #opens file with name of "test.txt"
print(f.read(1))
print(f.read())
f.close()

The important thing I saved until the end is that you should always close your files using the close() method. Python gets tired running around opening files and reading them, so give it a break and close the file to end the connection. It is always good practice to close files, your memory will thank you. Next, let's do some construction by writing to files.

For a more tangible and better look into the Python language, consider reading the following book. It's an excellent read.

Your code will execute in this window.



Let's explore some more tutorials or topics!

Next Tutorial Previous Tutorial

Advertisement

If you enjoyed this resource, support me by sharing this page with others.

Comment on

Show Comments
  • User

    DaveT June 16, 2016, 11:48 p.m.

    I'm trying through Coursera, how to get raw_input to read the user input so, it being a python 2 version name=raw_input("Please enter your name: ") print (name) But I didn't get the output it prompts for, so what do I do?

  • User

    Retic July 15, 2015, 4:04 a.m.

    f = open("test.txt","r") #opens file with name of "test.txt" print(f.read(1)) print(f.read())

  • User

    noneTfFinisher May 15, 2015, 8 a.m.

    Why is there no mention of the handling any file Exception errors? This needs to be added because it is part of standard programming.

  • User

    Aksinia April 13, 2015, 5:51 p.m.

    If you are using PyCharm, take a look at the left hand side (whre the list of projects) section and check location of your project (it will be shown next to a project name). This is a location where you need to put your file to make PyCharm to see it. After that you can play around with it and try your skills.

  • User

    flberger Jan. 15, 2015, 10:04 a.m.

    Always explicitly use `encoding = "utf8"` with `open()`. Always explicitly use `encoding = "utf8"` with `open()`. Always explicitly use `encoding = "utf8"` with `open()`. That's worth repeating three times. Otherwise Python will default to "current platform encoding", which might drive you into all sorts of encoding issues when you switch or move between operating systems. Trust me. I've been there. You might consider updating your tutorial to something like open("test.txt", "r", encoding = "utf8")

  • User

    Barak Dec. 10, 2014, 2:24 p.m.

    you can put the text in the List much faster! f=open("test.txt","r") myList=f.readlines() and that's it! the "readlines()" give you the list you need faster then the "reaqdline()" :)

  • User

    Adrian M Dec. 29, 2013, 10:48 p.m.

    ALSO! if you are having more problems, try using IDLE (downloaded along with python 3.3.3, i believe.), it is able to understand and run anything that the code simulator provided on this website can.

  • User

    Adrian M Dec. 29, 2013, 10:44 p.m.

    If you have a problem like the error i received (Traceback (most recent call last): File "<pyshell#219>", line 1, in <module> f = open("test.txt","r") FileNotFoundError: [Errno 2] No such file or directory: 'test.txt') just make SURE that your text file is in documents, not desktop (if using a mac osx)

  • User

    Nitish P Nov. 30, 2013, 9:10 a.m.

    Below feature of Python reading from files is awesome.In other languages this would involve many lines of coding but this is truly amazing... Loved it. f = open("test.txt","r") #opens file with name of "test.txt" myList = [] for line in f: myList.append(line) print(myList)

  • User

    Witt Holloway Nov. 23, 2013, 9:18 p.m.

    Lesson was helpful, but I was not able to test code using the code simulator (even when I created a test file in my Documents folder to practice with. Instead , I tested code (successfully) using IDLE. Perhaps I am missing something regarding the code simulator.

  • User

    Ben Brawn July 23, 2013, 6:03 a.m.

    "I am a test file. Maybe someday, he will promote me to a real file. Man, I long to be a real file and hang out with all my new real file friends." I lol-ed

  • User

    Elv02 July 7, 2013, 5:26 p.m.

    To people who have the File Not Found error in the future, I had this today as well, and fixed it. First, if your using a editor or IDE, you're directory is probably different from where you're saving files. Check it using os.getcwd() Example: import os print(os.getcwd()) #if it's wrong, fix it with os.chdir(path) os.chdir("C:/Users/YourName/FileLocation") #Check the path again, it will be fixed print(os.getcwd()) This fixed it for me

  • User

    Jared Drake April 11, 2013, 3:31 p.m.

    @Sky Falling I don't know exactly what your problem is, but I think you just need to make sure your text file is in the same directory as your python script.

  • User

    Sky Flying April 11, 2013, 3:04 p.m.

    f=open("test.txt", "r") # try to open from saved text.txt but it does not open, and it is error at below you can see. how? Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> f=open("test.txt", "r") FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

  • User

    Jared Drake March 30, 2013, 9:39 p.m.

    @Leiming Gu Nice catch! Sorry, its the syntax highlighter that doesn't recognize spaces in the editor. It's fixed now.

  • User

    Jared Drake Feb. 11, 2013, 5:36 p.m.

    @Robert T The issue with your code is that you don't actually print twice on line 2 you have: r = r = f.read(); #this does not print on line 5 you have: print(f.read()); #this will print Does that help?



Advertisement