# 18. File Handling

### What is File Handling ?

Till now We are taking input from console and interacting with console only . But sometimes data is too large to be shown on console.The data to be displayed may be very large, and only a limited amount of data can be displayed on the console since the memory is volatile.

The file handling plays an important role when the data needs to be stored permanently into the file. A file is a named location on disk to store related information. We can access the stored information (non-volatile) after the program termination.

The file-handling implementation is slightly lengthy or complicated in the other programming language, but it is easier and shorter in Python.

Hence, a file operation can be done in the following order:

1.Open a file with access mode\
\
2.Read or write - Performing operation\
\
3.Close the file

### Opening a file :

To perform any operation in file , we must need to open the file.

Files must be opened with an access mode.

Access mode means how do you want to access a particular file.

### Types of Access modes :

x - it is used to create a new file with specified name. It throws error if file name exists already.

r - It opens the file to read-only mode.The file is by default open in this mode if no access mode is passed.

w - It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name.

a - It opens the file in the append mode. The file pointer exists at the end of the previously written file if exists any. It creates a new file if no file exists with the same name.

r+ - It opens the file to read and write both. The file pointer exists at the beginning of the file.

w+ - It opens the file to write and read both. It is different from r+ in the sense that it overwrites the previous file if one exists whereas r+ doesn't overwrite the previously written file. It creates a new file if no file exists. The file pointer exists at the beginning of the file.

a+ - It opens a file to append and read both. The file pointer remains at the end of the file if a file exists. It creates a new file if no file exists with the same name.

### Creating a File :

If you want to create a file , You must use 'x' for access mode. Suppose i want to create a file with file name : Console on my desktop .

**Syntax : open(file-path , mode)**

```
f = open(r'C:\Users\abhi\Desktop\Console.txt','x')  #will create a file 'Console' in deskt
```

<figure><img src="https://2715416193-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FqrOwR7E0344TGTnSFHoL%2Fuploads%2Fy5f5vWuj6ZeZPxVtWODO%2Fimage.png?alt=media&#x26;token=3330b89a-2663-4f44-885c-cc57b5a4c581" alt=""><figcaption></figcaption></figure>

**Note:**&#x49;t will throw error if duplicate file is created with same name.

```
f = open(r'C:\Users\abhi\Desktop\Console.txt','x')
```

```
---------------------------------------------------------------------------
FileExistsError                           Traceback (most recent call last)
<ipython-input-7-37a6538c42b6> in <module>
----> 1 f = open(r'C:\Users\abhi\Desktop\Console.txt','x')

FileExistsError: [Errno 17] File exists: 'C:\\Users\\abhi\\Desktop\\Console.txt'
```

### Writing in a file with 'w' :

It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name.

let's start with a new file that we have created and is empty by now.

<figure><img src="https://2715416193-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FqrOwR7E0344TGTnSFHoL%2Fuploads%2Fjunvo4igTpGHdmXX7w6P%2Fimage.png?alt=media&#x26;token=17a94d7c-cb7a-4cee-8ac6-42c3f776e792" alt=""><figcaption></figcaption></figure>

To write in a we must open this file with right access mode. **w** or **a** is the right access mode for writing in an empty File.

```
f = open(r'C:\Users\abhi\Desktop\Console.txt','w')   #opening a file with access mode
f.write('''The file handling plays an important role when the data needs to be stored permanently into the file. 
A file is a named location on disk to store related information.
We can access the stored information (non-volatile) after the program termination.''')  #file operation
f.close()   #closing a file
```

<figure><img src="https://2715416193-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FqrOwR7E0344TGTnSFHoL%2Fuploads%2FwTp4hWaCDRjHhmobqHwz%2Fimage.png?alt=media&#x26;token=9208f57d-02fb-4838-9eeb-8143bca758e8" alt=""><figcaption></figcaption></figure>

If we write anything again in the same file , data in file will overwrite. for Example:

In \[9]:

```
f = open(r'C:\Users\abhi\Desktop\Console.txt','w')   #opening a file with access mode
f.write('''The file-handling implementation is slightly lengthy or complicated in the other programming language,
but it is easier and shorter in Python.''')  #file operation
f.close()   #closing a file
```

<figure><img src="https://2715416193-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FqrOwR7E0344TGTnSFHoL%2Fuploads%2FbiJR5zdyFUN5bHNGJh3f%2Fimage.png?alt=media&#x26;token=08bb5939-4d7a-433f-be70-c28295b7b122" alt=""><figcaption></figcaption></figure>

**'w'** overwrote data in Console File.

### Writing in a file with 'a' :

a - It opens the file in the append mode. The file pointer exists at the end of the previously written file if exists any. It creates a new file if no file exists with the same name.

let's try to append data in our 'Console' File :

In \[10]:

```
f = open(r'C:\Users\abhi\Desktop\Console.txt','a')
f.write("To perform any operation in file , we must need to open the file.")
f.close()
```

<figure><img src="https://2715416193-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FqrOwR7E0344TGTnSFHoL%2Fuploads%2FSQVJcT3Y15f6Z4qAxuw0%2Fimage.png?alt=media&#x26;token=ae019a05-d40e-48c0-bfef-eb352adfe887" alt=""><figcaption></figcaption></figure>

### Reading in a file with 'r' :

It opens the file to read-only mode.The file is by default open in this mode if no access mode is passed.

Let's try to read our Console file.

In \[11]:

```
f = open(r'C:\Users\abhi\Desktop\Console.txt','r')
data = f.read()
f.close()

print(data)
```

```
The file-handling implementation is slightly lengthy or complicated in the other programming language,
but it is easier and shorter in Python.To perform any operation in file , we must need to
```

### To convert data written in Console in upper case :

In \[12]:

```
f = open(r'C:\Users\abhi\Desktop\Console.txt','r')
data = f.read()
f.close()

data = data.upper()

f = open(r'C:\Users\abhi\Desktop\Console.txt','w')
f.write(data)
f.close()
```

<figure><img src="https://2715416193-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FqrOwR7E0344TGTnSFHoL%2Fuploads%2FFqwQQyGy33xraNtYsHdc%2Fimage.png?alt=media&#x26;token=5c3b97f3-805e-41b5-90c0-d85b2c9d1a37" alt=""><figcaption></figcaption></figure>

### Read file with loop :

In \[15]:

```
f = open(r'C:\Users\abhi\Desktop\Console.txt','r')  #opening file with read permission
for i in f:
    print(i)   #prints each line
```

```
The file-handling implementation is slightly lengthy or complicated in the other programming language,

but it is easier and shorter in Python.To perform any operation in file , we must need to open the file.
```

### Read lines of a file :

The readline() method reads the lines of the file from the beginning, i.e., if we use the readline() method two times, then we can get the first two lines of the file.

In \[17]:

```
f = open(r'C:\Users\abhi\Desktop\Console.txt','r') 
firstline = f.readline()
print(firstline)
f.close()
```

```
The file-handling implementation is slightly lengthy or complicated in the other programming language,
```
