Friday, July 31, 2020

Python file operation

In python, If we have a file then we can perform three types of operation like open a file, read or write operation a file, and close a file.


Opening a file: Python provides an open() function that accepts two arguments syntax is like below.

file object = open(<file-name>, <access-mode>, <buffering>) 


access-mode:

r: open a file for reading.
w: open a file writing, create if does not exist, truncate the file if it exists.
b: open a file in binary mode.
a: open a file for appending at the end of the file without truncating it, create a new file if does not exist.
t: open a file in text mode.
+: '+'open a file updating(reading and writing).


a file can perform below these operations at a time.

r,rb,r+,rb+

w,wb,w+,wb+

a,ab,a+,ab+


Some basic operation and example are below:


#opens the file file.txt in read mode    
file = open("file.txt","r")    
    
if file:    
    print("file is opened successfully")   

Output:
<class '_io.TextIOWrapper'>
file is opened successfully


The close() method:


Once all the operations are done on the file, we must close it through our Python script using the close() method.

syntax:
fileobject.close() 



# opens the file file.txt in read mode    
file = open("file.txt","r")    
    
if file:    
    print("file is opened successfully")    
    
#closes the opened file    
file.close()  


try:  
   file = open("file.txt")  
   # perform file operations  
finally:  
   file.close()



The with statement
The with statement was introduced in python 2.5. The with statement is useful in the case of manipulating the files. It is used in the scenario where a pair of statements is to be executed with a block of code in between.

syntax:
with open(<file name>, <access mode>) as <file-pointer>:    
    #statement suite 


example:

with open("file.txt",'r') as f:    
    data = f.read();    
    print(data)  


......................................................................................................................................................................
# open the file.txt in append mode. Create a new file if no such file exists.  
file = open("file2.txt", "w")  
  
# appending the content to the file  
file.write('''''Python is the modern day language. It makes things so simple. 
It is the fastest-growing programing language''')  
  
# closing the opened the file  
file.close()


conclusion: We have opened the file in w mode. The file1.txt file doesn't exist, it created a new file and we have written the content in the file using the write() function.




......................................................................................................................................................................
#open the file.txt in write mode.    
file = open("file2.txt","a")  
    
#overwriting the content of the file    
file.write(" Python has an easy syntax and user-friendly interaction.")    
      
#closing the opened file     
file.close()  


......................................................................................................................................................................

#open the file.txt in read mode. causes error if no such file exists.    
file = open("file2.txt","r")  
#stores all the data of the file into the variable content    
content = file.read(10)   
# prints the type of the data stored in the file    
print(type(content))      
#prints the content of the file    
print(content)       
#closes the opened file    
file.close()   


......................................................................................................................................................................


Read file through for loop:

#open the file.txt in read mode. causes an error if no such file exists.    
file = open("file2.txt","r");     
#running a for loop     
for i in file:    
    print(i) # i contains each line of the file 




Reading lines using readline() function:

#open the file.txt in read mode. causes error if no such file exists.    
file = open("file2.txt","r");     
#stores all the data of the file into the variable content    
data = file.readline()     
data1 = file.readline()  
#prints the content of the file    
print(content)     
print(content1)  
#closes the opened file    
file.close()    


Creating a new file:


#open the file.txt in read mode. causes error if no such file exists.    
file = open("file2.txt","x")   
print(fileptr)    
if file:    
    print("File created successfully")



......................................................................................................................................................................

File Pointer positions:

Python provides the tell() method which is used to print the byte number at which the file pointer currently exists.


# open the file file2.txt in read mode    
file = open("file2.txt","r")    
  
#initially the filepointer is at 0     
print("The filepointer is at byte :",file.tell())    
    
#reading the content of the file    
content = file.read();    
    
#after the read operation file pointer modifies. tell() returns the location of the file.     
    
print("After reading, the filepointer is at:",file.tell()) 


......................................................................................................................................................................

Modifying file pointer position:

sometimes we need to change the file pointer location externally since we may need to read or write the content at various locations. For this purpose, the Python provides us the seek() method which enables us to modify the file pointer position externally.

<file-ptr>.seek(offset[, from)


offset: It refers to the new position of the file pointer within the file.

from: It indicates the reference position from where the bytes are to be moved. If it is set to 0, the beginning of the file is used as the reference position. If it is set to 1, the current position of the file pointer is used as the reference position. If it is set to 2, the end of the file pointer is used as the reference position.

# open the file file2.txt in read mode    
file = open("file2.txt","r")    
    
#initially the filepointer is at 0     
print("The filepointer is at byte :",file.tell())    
    
#changing the file pointer location to 10.    
file.seek(10);    
    
#tell() returns the location of the file.     
print("After reading, the filepointer is at:",fileptr.tell())

......................................................................................................................................................................

Python OS module:

Renaming the file:

It provides us the rename() method to rename the specified file to a new name.

syntax:

rename(current-name, new-name)

import os    
    
#rename file2.txt to file3.txt    
os.rename("file2.txt","file3.txt")

Removing the file:

The os module provides the remove() method which is used to remove the specified file.

import os;    
#deleting the file named file3.txt     
os.remove("file3.txt")


Creating the new directory:

The mkdir() method is used to create the directories in the current working directory. The syntax to create the new directory is given below.

import os    
    
#creating a new directory with the name new    
os.mkdir("new")  


The getcwd() method:

This method returns the current working directory.

import os  
os.getcwd()

Changing the current working directory:

The chdir() method is used to change the current working directory to a specified directory.

import os   
# Changing current directory with the new directiory  
os.chdir("C:\\Users\\DEVANSH SHARMA\\Documents")  
#It will display the current working directory  
os.getcwd() 

Deleting directory:

The rmdir() method is used to delete the specified directory.

import os  
#removing the new directory     
os.rmdir("directory_name")



Writing Python output to the files:

In Python, there are the requirements to write the output of a Python script to a file.

The check_call() method of module subprocess is used to execute a Python script and write the output of that script to a file.

file.py
temperatures=[10,-20,-289,100]    
def c_to_f(c):    
    if c< -273.15:    
        return "That temperature doesn't make sense!"    
    else:    
        f=c*9/5+32    
        return f    
for t in temperatures:    
    print(c_to_f(t))


----------------------------------------------------------------------------------------------------------------------------
file.py

import subprocess    
    
with open("output.txt", "wb") as f:    
    subprocess.check_call(["python", "file.py"], stdout=f) 



2 comments: