File Manipulation
File Manipulation
FILE MANIPULATIONS
File manipulation means change or access the content in the file.
File Positions
Renaming and Delete a File
Directories in Python
1. File Positions
There are two methods to access the positions of the file.
1. tell()
2.seek()
i) tell() method
This method is used to tell the current position within a file. It starts from the beginning
of the file and this method followed by read() and write() method.
Syntax:
file_object.tell()
The default argument of offset is 0. The offset represents the number of the bytes to be
moved.
The from argument represents three values.
0 represents the beginning of the file
1 represents the current position as reference
2 represents the end of the file
f1=open("F:/Python/sample.txt","r")
str=f1.read(10)
print(“read string is : “,str)
position=f1.tell()
print(“current file position:”,position)
position=f1.seek(0,0)
str=f1.read(10)
print(“again read string is :”,str)
f1.close()
Output:
os.rename(current_filename, new_filename)
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING
ROHINI COLLEGE OF ENGINEERING & TECHNOLOGY
Syntax:
Example
import os
os.rename(“test.txt”,”new.txt ”)
os.remove(filename)
Example:
import os
os. remove(“new.txt ”)
DIRECTORIES IN PYTHON
All files are contained within various directories. The os module has several methods to
create, remove and change directories.
FORMAT OPERATOR
The argument of write has to be a string, so if we want to put other values in a file, we
have to convert them to strings. The easiest way to do that is with str:
f=open('stringsample.txt','w')
f.write(5) #TypeError
f.write(str(5))
An alternative is to use the format operator, %. The first operand is the format string,
which contains one or more format sequences, which specify how the second operand is
formatted. The result is a string.
Example:
var=8
print("The Value is : %d"%var)
Output:
The Value is : 8