Python Data File Handling
operations on text file
A text file consists of a sequence of lines. A line is a sequence of characters, stored on permanent storage. In a text file, each line is terminated by a special character, known as End Of Line (EOL). Text file can be created using any text editor. Ex. Myfile.txt.
Opening a text file: Open ()
When we want to read or write a file, we must have to open is first. Open () function takes the name of a file as the first argument. The second argument indicates the mode of accessing the file.
<file variable>=open(file name, access mode)
Modes for opening a file:
read(r) : to read the file
write(w): to write the file
append(a): to write at the end of file
<_io.TextIOWrapper name='myfile.txt' mode='r' encoding='cp1252'>
Closing file: close()
f=open('myfile.txt') print("The file which is to be open using the given command is:",f.name) f.close()
The file which is to be open using the given command is: myfile.txt
Properties of File Object:
name: shows the file name of opened file
mode: shows Mode in which the file gets opened
readable: returns Boolean value, which indicates whether the file is readable or not
closed: returns Boolean value, which indicates whether the file is closed or not
f=open('myfile.txt', 'w') print("Name of File:",f.name) print("Mode of File:",f.mode) print("File readable :",f.readable()) print("File closed:",f.closed) f.close() print("File closed:",f.closed, f.name)
Name of File: myfile.txt Mode of File: w File readable : False File closed: False File closed: True myfile.txt
Reading form a file:
We can read character data from text file by using the following read methods:
read(): To read the entire data from the file; starts reading from the cursor up to the end of the file.
The text file named myfile.txt is already stored in my local disk with the data shown in image.
f=open('myfile.txt', 'r') data=f.read() print(data) f.close()
== RESTART: C:/Users/ATC/AppData/Local/Programs/Python/Python38-32/filehandling.py = Hello, Welcome to the CBSE class 12 students Having computer science with python You are learning Python file handling >>>
read(n): To read ‘n’ characters from the file, starting from the cursor.
Example: Here we will read only first 21 characters from the file.
f=open('myfile.txt', 'r') data=f.read(21) print(data) f.close()
Hello, Welcome to the
readline(): To read only one line from the file; starts reading from the cursor up to, and including, the end of line character.
readlines(): To read all lines from the file into a list; starts reading from the cursor up to the end of the file and returns a list of lines.