UNIT-V - Part-2 (Files)
UNIT-V - Part-2 (Files)
Solving
Unit-5: Files
Opens a file for appending at the end of the file without truncating it.
a
Creates a new file if it does not exist.
try:
f = open("test.txt", encoding = 'utf-8')
# perform file operations
finally:
f.close()
• To create a new file in Python, use the open() method, with one of the
following parameters:
• "x" - Create - will create a file, returns an error if the file exist
• "a" - Append - will create a file if the specified file does not exist
• "w" - Write - will create a file if the specified file does not exist.
Ex:
f=open("myfile.txt", "x")
f=open("myfile.txt", "w")
f=open("myfile.txt", “a")
• The method tell() returns the current position of the file read/write pointer
within the file.
Syntax: fileObject.tell()
Ex:
f= open('one.txt','r')
print(f.readline())
print(f.tell())
o/p:
Hi this is cse
16
Ex:
f= open('one.txt','r')
print(f.readline()) #o/p: hi this is cse
f.seek(3,0)
print(f.readline()) #o/p: this is cse
Syntax:
os.rename(oldname,newname)
Ex:
import os
os.rename("one2.txt","two.txt")