Interact with files in Python

This article will focus on the following topics.

Creating a file

The first step is to use an instance of the — open a file on disk. In any computer language, this means establishing a link between your code and an external file. The open () member function is provided to create a new I / O class file.

Syntax :

 open (filename, mode) 

Here, mode refers to the access mode. Access modes determine the type of possible operations in an open file. This refers to how the file will be used after opening it. These modes also determine the location of the file descriptor in the file. A file descriptor is like a cursor that defines where data should be read from or written to the file. Python has 6 access modes.

  • Read only (& # 39; r & # 39;): open a text file for reading. The descriptor is located at the beginning of the file. If the file does not exist, an I / O error occurs. This is also the default mode in which the file is opened.
  • Read and Write (& # 39; r + & # 39;): open the file for reading and writing. The descriptor is located at the beginning of the file. Throws an I / O error if the file does not exist.
  • Write only (& # 39; w & # 39;): open file for writing. For an existing file, data is truncated and overwritten. The descriptor is located at the beginning of the file. Creates a file if the file does not exist.
  • Write and Read (& # 39; w + & # 39;): open the file for reading and writing. For an existing file, data is truncated and overwritten. The descriptor is located at the beginning of the file.
  • Append only (& # 39; a & # 39;): open the file for writing. The file is created if it doesn`t exist. The descriptor is located at the end of the file. The data to be written will be inserted at the end, after the existing data.
  • Add and Read (& # 39; a + & # 39;): open the file for reading and writing. The file is created if it doesn`t exist. The descriptor is located at the end of the file. The data being written will be inserted at the end, after the existing data.

Example: Let`s assume the folder looks like this —

# Open the function to open the file & quot; MyFile1.txt & quot;
# (same directory) in add mode and

file1 = open ( "MyFile. txt " , " w + "

Exit:

In the above example, the open () function along with the access mode UPA “w +” is used to open a file in read and write mode, but if the file does not exist on the computer system, it creates a new file.

Note. To learn more about creating file,

# Program for showing different ways
# read data from a file.

 
# Create file

file1 = open ( "myfile.txt" , " w "

L = [ "This is Delhi" , "This is Paris" , "This is London"

 
# Writing data to file

file1. write ( "Hello"

file1 .writelines (L) 

file1.close ()  # change file access mode

 

file1 = open ( "myfile.txt" , "r +"

 

print ( "Output of Read function is"

print (file1.read ()) 

print () 

 
# seek (n) translates the file descriptor to nth
# bite from the beginning.

file1.seek ( 0

 

print ( "Output of Readline function is "

print (file1. readline ()) 

prin t () 

 

file1.seek ( 0

  
# To show the difference between read and readline

print ( "Output of Read (9) function is"

print (file1.read ( 9 )) 

print () 

 

file1.seek ( 0

 

print ( " Output of Readline (9) funct ion is "

print (file1 .readline ( 9 )) 

print () 

 

file1.seek ( 0

  
# readlines

print ( "Output of Readlines function is"

print (file1.readlines ()) 

print () 

file1.close () 

Output:

 Output of Read function is Hello This is Delhi This is Paris This is London Output of Readline function is Hello Output of Read (9) function is Hello Th Output of Readline (9) function is Hello Output of Readlines function is [`Hello`, `This is Delhi`, ` This is Paris `,` This is London `] 

Note. To learn more about reading from a file, click here .

Write to file

There are two ways to write to a file.

  1. write (): Inserts str1 on one line in a text file. 
    File_object.write (str1)
  2. writelines (): for a list of string items, each line is inserted into a text file. Used to insert multiple lines at the same time. 
    File_object.writelines (L) for L = [str1, str2, str3]

Note: & # 39; / n & # 39; is treated as a two-byte special character.

# Python program for demonstration
# write to file

  
# Open file

file1 = open ( `myfile.txt` , ` w`

L = [ "This is Delhi" , "This is Paris" , " This is London "

s = " Hello "

  
# Write line to file
file1.write (s) 

 
# Writing multiple lines
# on time
file1.writelines (L) 

 
# Closing the file
file1.close () 

 
# Checking data
# written to file or not

file1 = open ( `myfile.txt` , ` r`

print (file1.read ()) 

file1.close () 

Exit :

 Hello This is Delhi This is Paris This is London 

Note. To find out for more on writing to a file,

Inside G:

# Python navigation program
# files

 

 

import shutil 

 
# Source path

source = "D: Pych arm projectsgfgTestTest4.txt "

  
# Destination path

destination = "D: Pycharm projectsgfgTestG"

 
# Move content
# source to destination

dest = shutil.move (source, destination) 

 
# print (dest) prints
# Purpose of the moved directory

Exit:

Note. To learn more about moving files, click here .

Deleting a File

os.remove () in Python is used to remove or remove a file path. This method cannot delete or delete a directory. If the specified path is a directory, the method will raise OSError.

Example: Assuming the file contained in the folder:

We want to delete file1 from the above folder. Below is the implementation.

# Python program to explain the os.remove () method

 
# import of the os module

import os 

 
# File name

file = `file1.txt`

 
# File location

location = " D: / Pycharm projects / Python.Engineering / Authors / Nikhil / "

 
# Path

path = os.path.join (location, file

 
# Delete file
# & # 39; file.txt & # 39;
os.remove (path) 

Exit:

Note. To learn more about deleting files, click here .