Pyexp 7
Pyexp 7
Experiment No.7
Aim: Write a program to implement File and directories
INTRODUCTION
File handling in Python allows users to read, write, and manipulate files stored on a system. It provides
built-in functions to handle text and binary files efficiently. Python treats files as streams:
DATA FILES
Data files store structured information, which can be read and processed using Python. Python
supports different file formats like text files (.txt), CSV files (.csv), JSON files (.json), etc.
Syntax:
file = open("filename.txt", "mode")
# File operations
file.close()
Example:
file = open("data.txt", "w") # Creates a text file
file.write("Hello, Python File Handling!")
file.close()
Syntax:
file = open("filename.txt", "mode") # Open file
file.close() # Close file
Example:
file = open("sample.txt", "w")
file.write("This is a sample file.")
file.close()
Python provides methods like read(), readline(), and readlines() to read files and write() or writelines() to write
data.
Syntax:
# Writing to a file
file = open("filename.txt", "w")
file.write("Content")
file.close()
Syntax:
import sys
# Standard input
data = sys.stdin.read()
# Standard output
sys.stdout.write("Output message\n")
# Standard error
sys.stderr.write("Error message\n")
Example:
import sys
sys.stdout.write("This is standard output.\n")
sys.stderr.write("This is an error message.\n")
Program:
import os
# 1. Opening a file in 'w+' mode (write and read)
file = open('yashodeep.txt', 'w+')
# 2. Writing to the file
file.write('AI is the future.\n')
file.write('It is transforming industries.\n')
# 3. Writing multiple lines
file.writelines(['Automation is key.\n', 'Ethical AI matters.\n'])
# 4. Moving cursor to the start and reading content
file.seek(0)
print('--- Full Content ---')
print(file.read())
# 5. Reset cursor and read line by line
file.seek(0)
print('--- Line by Line ---')
for line in file:
print(line.strip())
# 6. Reset cursor and read all lines into a list
file.seek(0)
print('--- List of Lines ---')
print([line.strip() for line in file.readlines()])
# 7. Closing the file
file.close()
# 8. Appending new content
with open('yashodeep.txt', 'a') as file:
file.write('AI will evolve further.\n')
# 9. Reading updated content
with open('yashodeep.txt', 'r') as file:
print('--- Updated Content ---')
print(file.read())
# 10. Checking file existence
if os.path.exists('yashodeep.txt'):
print('File exists.')
# 11. Renaming the file
os.rename('yashodeep.txt', 'ai_data.txt')
print('File renamed to ai_data.txt')
# 12. Deleting the file
os.remove('ai_data.txt')
print('File ai_data.txt deleted.')
Output: