File Handling
File Handling
File handling in Python refers to the process of working with files on your
computer's storage system.
Python provides built-in functions and modules that allow you to create, read,
write, and manipulate files.
It requires the file name and the mode in which you want to open the file (read,
write, append, etc.).
Once you're done working with the file, it's good practice to close it using the
close() method
'w': Write mode. Opens a file for writing. Creates a new file or truncates the
existing content.
'a': Append mode. Opens a file for writing at the end. Creates a new file if it
doesn't exist.
'b': Binary mode. Opens a file in binary mode (e.g., 'rb' for reading binary
files).
# Writing to a File
file = open(r'C:\Users\Ajit\Downloads\bank\name.txt', 'w')
file.write('Hello, this is a sample text.')
file.close()
file=open(r'C:\Users\Ajit\Downloads\bank\ajit.txt')
file
content=file.read()
print(content)
file
print(content)
file
file
print(content)
file_path = r'C:\Users\Ajit\Downloads\bank\save.txt'
file.readline() reads a single line from the file each time it's called.
The while line: loop continues until the variable line is an empty string, which
happens when there are no more lines to read.
Inside the loop, print(line.strip()) displays the line content using print().
.strip() removes any leading or trailing whitespace characters (like spaces, tabs,
or newline characters) from the line before printing it.
line = file.readline() reads the next line, and the process continues until the end
of the file is reached.
# Writing to a File in readline()
file_path = r'C:\Users\Ajit\Downloads\bank\name.txt'
# Writing to a file
file_path = r'C:\Users\Ajit\Downloads\bank\name.txt'
line=file.readline()
while line:
print(line.strip())
line=file.readline()