In this tutorial, you will learn how to open a file, write to the file, and close it. You will also learn how to read from the file using Python. Show
By the end of this tutorial, you should know the basics of how to use files in Python. File Handling in PythonFile handling is an important activity in every web app. The types of activities that you can perform on the opened file are controlled by Access Modes. These describe how the file will be used after it has been opened. These modes also specify where the file handle should be located within the file. Similar to a pointer, a file handle indicates where data should be read or put into the file. In Python, there are six methods or access modes, which are:
Below is the code required to create, write to, and read text files using the Python file handling methods or access modes. How to Create Files in PythonIn Python, you use the 0 function with one of the following options – "x" or "w" – to create a new file:
Example of creating a file in Python using the "x" command:
We've now created a new empty text file! But if you retry the code above – for example, if you try to create a new file with the same name as you used above (if you want to reuse the filename above) you will get an error notifying you that the file already exists. It'll look like the image below:
Example of how to create a file with the "w" command:
With the code above, whether the file exists or the file doesn't exist in the memory, you can still go ahead and use that code. Just keep in mind that it will overwrite the file if it finds an existing file with the same name. How to Write to a File in PythonThere are two methods of writing to a file in Python, which are: The #creating a text file with the command function "w" f = open("myfile.txt", "w") #This "w" command can also be used create a new file but unlike the the "x" command the "w" command will overwrite any existing file found with the same file name.1 method:This function inserts the string into the text file on a single line. Based on the file we have created above, the below line of code will insert the string into the created text file, which is "myfile.txt.”
The #creating a text file with the command function "w" f = open("myfile.txt", "w") #This "w" command can also be used create a new file but unlike the the "x" command the "w" command will overwrite any existing file found with the same file name.2 method:This function inserts multiple strings at the same time. A list of string elements is created, and each string is then added to the text file. Using the previously created file above, the below line of code will insert the string into the created text file, which is "myfile.txt.”
Example:
How to Read From a Text File in PythonThere are three methods of reading data from a text file in Python. They are: The #creating a text file with the command function "w" f = open("myfile.txt", "w") #This "w" command can also be used create a new file but unlike the the "x" command the "w" command will overwrite any existing file found with the same file name.3 method:This function returns the bytes read as a string. If no n is specified, it then reads the entire file. Example:
The readline() method:This function reads a line from a file and returns it as a string. It reads at most n bytes for the specified n. But even if n is greater than the length of the line, it does not read more than one line.
The #creating a text file with the command function "w" f = open("myfile.txt", "w") #This "w" command can also be used create a new file but unlike the the "x" command the "w" command will overwrite any existing file found with the same file name.4 method:This function reads all of the lines and returns them as string elements in a list, one for each line. You can read the first two lines by calling 5 twice, reading the first two lines of the file:
How to Close a Text File in PythonIt is good practice to always close the file when you are done with it. Example of closing a text file:This function closes the text file when you are done modifying it:
The close() function at the end of the code tells Python that well, I am done with this section of either creating or reading – it is just like saying End. Example:The program below shows more examples of ways to read and write data in a text file. Each line of code has comments to help you understand what's going on:
This is the output of the above code when run in the shell. I assigned "This is Lagos", "This is Python", and "This is Fcc" to "L" and then asked it to print using the ''file.read'' function. The code above shows that the "readline()" function is returning the letter based on the number specified to it, while the "readlines()" function is returning every string assigned to "L" including the \n. That is, the "readlines()" function will print out all data in the file. ConclusionHopefully, after going through this tutorial, you should understand what file handling is in Python. We also learned the modes/methods required to create, write, read, and close() a text file using some basic examples from Python. Thanks for reading! ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT Software engineer, Technical writer, and Web 3.0 enthusiasts If you read this far, tweet to the author to show them you care. Tweet a thanks Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started |