Python File Open

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

File Handling

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist.

"a" - Append - Opens a file for appending, creates the file if it does not exist.

"w" - Write - Opens a file for writing, creates the file if it does not exist.

"x" - Create - Creates the specified file, returns an error if the file exists.

'r'  open for reading (default)
'w'  open for writing, truncating the file first
'x'  create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode.

"b" - Binary - Binary mode (e.g. images).

Syntax

To open a file for reading it is enough to specify the name of the file:

The code above is the same as:

Because "r" for read, and "t" for text are the default values, you do not need to specify them.

Note: Make sure the file exists, or else you will get an error.

Open a File on the Server

Assume we have the following file, located in the same folder as Python:

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the content of the file:

Best choice:

Optional solutions:

Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many characters you want to return:

You can return one line by using the readline() method:

By calling readline() two times, you can read the two first lines:

By looping through the lines of the file, you can read the whole file, line by line:

Close Files

Warning: Calling f.write() without using the with keyword or calling f.close() might result in the arguments of f.write() not being completely written to the disk, even if the program exits successfully.

It is a good practice to always close the file when you are done with it.

Close the file when you are finish with it:

Note: You should ALWAYS close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.

With method:

Close the file automatically:

Why you need to close the file

The I/O limitation is differ in different computers. In my computer, I cannot open more than 10490 files. If you don’t close it, the file will keep opening.

Linux Word Count

-w is for counting the number of words.

Python File Write

To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Note: the “w” method will overwrite the entire file.

Python Create File

To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exist.

"a" - Append - will create a file if the specified file does not exist.

"w" - Write - will create a file if the specified file does not exist.

Python Delete File

Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

Remove the file “demofile.txt”:

Check if File exist:

To avoid getting an error, you might want to check if the file exists before you try to delete it:

Delete Folder

To delete an entire folder, use the os.rmdir() method:

Note: You can only remove empty folders.

One More Thing

Python Algorithms - Words: 2,640

Python Crawler - Words: 1,663

Python Data Science - Words: 4,551

Python Django - Words: 2,409

Python File Handling - Words: 1,533

Python LeetCode - Words: 9

Python Machine Learning - Words: 5,532

Python MongoDB - Words: 32

Python MySQL - Words: 1,655

Python OS - Words: 707

Python plotly - Words: 6,649

Python Quantitative Trading - Words: 353

Python Tutorial - Words: 25,451

Python Unit Testing - Words: 68