Python Online Compiler

Files in Python

file

FIle is a collection of data or information which is used to store the data permanently.
Types of files:
1.Text Files
2.Document Files
3.Audio Files
4.Video Files
5.PDF Files ...
etc.....

File Operations
1.Open or create a file
2.Write the data into the file
3.Read the data from the file
4.close a file

Open file

Syntax:

f=open("Rain.txt") # Open file in curent Directory

f=open("c:/Python33/Rain.txt") # specifying full path

Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −
Sno Mode Description
1 r Opens an existing text file for reading purpose.
2 w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file.
3 a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content.
4 r+ Opens a text file for both reading and writing.
5 w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist.
6 a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
7 t Open in text Mode
8 b Open in binary Mode
9 + Open a file for updating (reading and writing)

f=open("Rain.txt",'r') # # equivalent to 'r' or 'rt'

f=open("Rain.txt",'w') # write in text mode

f=open("image.png",'r+b') # read and write in binary mode

Unlike other languages, the character 'a' does not imply the number 97 until it is encoded using ASCII (or other equivalent encodings).
Moreover, the default encoding is platform dependent. In windows, it is 'cp1252' but 'utf-8' in Linux.
So, we must not also rely on the default encoding or else our code will behave differently in different platforms.
Hence, when working with files in text mode, it is highly recommended to specify the encoding type.

f=open("Rain.txt",'w' ,encoding='utf-8')

Closing File

f=open("Rain.txt",'w', encoding='utf-8')
# perform file operations
f.close()

Writing File

f=open("Rain.txt",'w', encoding='utf-8')
f.write("Welcome to mak tutorials")
f.close()


OR

with open("Rain.txt",'w', encoding='utf-8') as f:
             f.write("Welcome to mak tutorials")

Reading File

f=open("Rain.txt",'r', encoding='utf-8')
print(f.read(10)) # Read the first 10 Characters
f.close()

f=open("Rain.txt",'r', encoding='utf-8')
print(f.read()) # Read the total file
f.close()

f=open("Rain.txt",'r', encoding='utf-8')
print(f.tell()) # it returns the our current position
f.close()

f=open("Rain.txt",'r', encoading='utf-8')
print(f.seek(0)) # bring the cursor to initial position
f.close()

f=open("Rain.txt",'r', encoding='utf-8')
print(f.readline()) # it is used to read the single line
f.close()

f=open("Rain.txt",'r', encoding='utf-8')
print(f.readlines()) # it is used to read the entire document
f.close()

Python File Methods

There are various methods available with the file object. Some of them have been used in above examples.

Here is the complete list of methods in text mode with a brief description.

Python File Methods
Method Description
close() Close an open file. It has no effect if the file is already closed.
detach() Separate the underlying binary buffer from the TextIOBase and return it.
fileno() Return an integer number (file descriptor) of the file.
flush() Flush the write buffer of the file stream.
isatty() Return True if the file stream is interactive.
read(n) Read atmost n characters form the file. Reads till end of file if it is negative or None.
readable() Returns True if the file stream can be read from.
readline(n=-1) Read and return one line from the file. Reads in at most n bytes if specified.
readlines(n=-1) Read and return a list of lines from the file. Reads in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Change the file position to offset bytes, in reference to from (start, current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
truncate(size=None) Resize the file stream to size bytes. If size is not specified, resize to current location.
writable() Returns True if the file stream can be written to.
write(s) Write string s to the file and return the number of characters written.
writelines(lines) Write a list of lines to the file.