Image

File - It is the information that is kept in the computer storage device. File is divided in two categories text file and binary file. Text file are the simple text and the binary file contain binary data which can only be read by the computer. File opening - To open a file use open() function. It contains two arguments, the file name or the file path and the mode. Mode can be read mode, write mode or the append mode.

In read mode we can read the file. In write mode the original content of the file get deleted and new data can be written in append mode we can add something or append to the original file by default the file open in read mode. The close() function-to close a file after the work has been done.

It is a good practice to close the file after working on it. There is an upper limit to the number of file a program can open. To learn more about file handling in python visit Python Training in Pune. If the limit is exceeded then there is no chance of recovery and the program stops. The memory is also wasted when many files are opened.

With Statement:

With statement take the care of closing the file. There is no need to close the file explicitly. After reading the file if we again try to read it then it will give an empty string. The readline() method will be used to read the file line by line

To write a file-

Open the file in write mode

File=open(‘filename’,’w’)

File.write(‘anything’)

The original data in the file has been removed and new data will be added copy file-a text from one file can be copied to another. File Handling in Python, the readlines() method return the list of line and the readline() return one line. Write() to write a fixed sequence of character to a file and writelines() to write the list of string. In python any type of file can be opened, read and appended. To open a csv File in Python use numpy and pandas library and make a dataframe to read and append to a file. Make a data frame out of the data in the file and then read and append the file through that data frame. 

Df=pd.read_csv(“filename”)

Df-dataframe

We can also read excel file, html file or any other file with the same format to give the output to a file, write df.to_csv(‘filename’). Pandas can read excel file and it only import data.