Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - File Handling

Python

python logo

In this tutorial we will learn to work with files in Python.

Create a new file

We use the open function to create a new file in Python.

The open function takes two arguments. The first argument is the name of the file to be created. The second argument is the mode and it is set to x.

In the following Python program we are creating a file by the name helloworld.txt.

# create a new file
fObj = open("helloworld.txt", "x")

fObj.close()

In the above code we are creating a file using the open() function.

It is a good practice to flush any unwritten data and close the file using the close() function.

If the file already exists then open("filename", "x") will return an error.

If we run the above code again we will get the following error as the file helloworld.txt exists.

Traceback (most recent call last):
  File "/Users/yusufshakeel/PycharmProjects/HelloWorld/files/file.py", line 2, in <module>
    fObj = open("helloworld.txt", "x")
FileExistsError: [Errno 17] File exists: 'helloworld.txt'

Create file using absolute path

We can also use the absolute file path to create files.

In the following Python program we are creating hello.txt file using absolute path.

# create a new file
fObj = open("/Users/yusufshakeel/PycharmProjects/HelloWorld/files/hello.txt", "w")

fObj.close()

Check if file exists

To check if a given file exists we have to use the os module.

In the following Python program we are importing the os module and then checking the existence of a given file.

# import module
import os

# check
if os.path.exists("helloworld.txt"):
    print("File exists")
else:
    print("File does not exists")

Write in a file

To write data in a file we use the open function in write w mode. Then we use the write function to write the data.

If the file does not exists then open("filename", "w") will create the file.

In the following Python program we are opening the helloworld.txt file in write mode and writing "Hello World" string in the file.

# open file
fObj = open("helloworld.txt", "w")

# write data
fObj.write("Hello World\n")

fObj.close()

If we open the helloworld.txt we will get to see the "Hello World" line in the file.

In the above code we are using new line \n escape sequence.

Append to a file

To append data to a file we use the open function and set the mode to a append mode.

If the file does not exists then open("filename", "a") will create the file.

In the following Python program we are opening the helloworld.txt file in append mode and appending string "Some more text." to the file.

# open file
fObj = open("helloworld.txt", "a")

# append data
fObj.write("Some more text.\n")

fObj.close()

Read file

To read the content of a file we use the open function with r read mode.

If the file does not exists then open("filename", "r") will return error.

In the following Python program we are reading the content of the helloworld.txt file that we have created earlier.

# open file
fObj = open("helloworld.txt", "r")

# read data
data = fObj.read()

# output
print(data)

fObj.close()

The above code will give use a similar output.

Hello World
Some more text.

Note! Your output may vary based on what you have written in the file.

The read function

By default, the read function will read all the content of the file.

If we want to read limited number of characters then we can pass numbers to the function.

In the following Python program we are reading only 5 characters of the helloworld.txt file.

# open file
fObj = open("helloworld.txt", "r")

# read data
data = fObj.read(5)

# output
print(data)

fObj.close()

The above code will give us a similar output.

Hello

The readline function

We use the readline function to read file one line at a time.

In the following Python program we are printing the first two lines of the helloworld.txt file using the readline function.

# open file
fObj = open("helloworld.txt", "r")

# read 1st line
data = fObj.readline()

# output
print(data)

# read 2nd line
data = fObj.readline()

# output
print(data)

fObj.close()

Each time we use readline function it reads a line and then moves to the next line.

Read file line by line

To read file line by line we can take help of for loop.

In the following Python program we are reading the content of the helloworld.txt file line by line using for loop.

# open file
fObj = open("helloworld.txt", "r")

for line in fObj:
    print(line)

fObj.close()

Delete a file

To delete a file we use the remove function from the os module.

In the following Python program we are removing the hello.txt file that we created earlier.

# import module
import os

# check and remove
if os.path.exists("hello.txt"):
    print("File exists... Removing it...")
    os.remove("hello.txt")
else:
    print("File does not exists")