Skip to content

File Handling

surendrabisht edited this page Jul 13, 2020 · 1 revision

Short Program to open file


import os
f = open(‘myfile.txt’, 'r')
firstline = f.readline()
secondline = f.readline()
print (firstline)
print (secondline)
f.close()  

File Open Modes

  • 'r' mode: For reading only.
  • 'w' mode: for writing only. If the specified file does not exist, it will be created.If the specified file exists, any existing data on the file will be erased.
  • 'a' mode:
    For appending. If the specified file does not exist, it will be created. If the specified file exist, any data written to the file is automatically added to the end
  • 'r+' mode:
    For both reading and writing.

for deleting file
os.remove(‘myfile.txt’)

# to rename file
os.rename(‘oldfile.txt’, ‘newfile.txt’)

there are other commands as well like mkdir, chdir(), etc.

Clone this wiki locally