[go: up one dir, main page]

0% found this document useful (0 votes)
13 views5 pages

Write To A File

The document provides a comprehensive guide on file operations in Python, including writing, reading, appending, and deleting files, as well as handling directories and JSON/CSV data. Each operation is accompanied by code examples and expected outputs. It also covers exception handling and custom functions for file operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views5 pages

Write To A File

The document provides a comprehensive guide on file operations in Python, including writing, reading, appending, and deleting files, as well as handling directories and JSON/CSV data. Each operation is accompanied by code examples and expected outputs. It also covers exception handling and custom functions for file operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

1.

Write to a File
Code:

with open("file1.txt", "w") as f:


f.write("Hello, World!")

Expected Output: (File created with content)


Content of file1.txt: Hello, World!

2. Read from a File


Code:

with open("file1.txt", "r") as f:


content = f.read()
print(content)

Expected Output:
Hello, World!

3. Append to a File
Code:
with open("file1.txt", "a") as f:
f.write("\nAppending this line.")

Expected Output: (File updated)


Content of file1.txt:
Hello, World!
Appending this line.

4. Read File Line by Line


Code:
with open("file1.txt", "r") as f:
for line in f:
print(line.strip())

Expected Output:
Hello, World!
Appending this line.

5. Write Multiple Lines to a File


Code:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("file2.txt", "w") as f:
f.writelines(lines)

Expected Output: (File created with multiple lines)


Content of file2.txt:
Line 1
Line 2
Line 3

6. Read All Lines into a List


Code:
with open("file2.txt", "r") as f:
lines = f.readlines()
print(lines)

Expected Output:
['Line 1\n', 'Line 2\n', 'Line 3\n']
7. Count Lines in a File
Code:
with open("file2.txt", "r") as f:
line_count = sum(1 for line in f)
print(line_count)

Expected Output:
3

8. Copy a File
Code:
import shutil
shutil.copy("file2.txt", "file2_copy.txt")

Expected Output: (File copied)


Content of file2_copy.txt:
Line 1
Line 2
Line 3

9. Rename a File
Code:
import os
os.rename("file2_copy.txt", "file2_renamed.txt")

Expected Output: (File renamed)


File renamed to file2_renamed.txt

10. Delete a File


Code:
os.remove("file2_renamed.txt")

Expected Output: (File deleted)


file2_renamed.txt deleted.

11. Check if a File Exists


Code:
if os.path.exists("file1.txt"):
print("file1.txt exists.")
else:
print("file1.txt does not exist.")

Expected Output:
file1.txt exists.

12. Get File Size


Code:
file_size = os.path.getsize("file1.txt")
print(f"Size of file1.txt: {file_size} bytes")

Expected Output:
Size of file1.txt: 27 bytes

13. Read a File in Binary Mode


Code:
with open("file1.txt", "rb") as f:
content = f.read()
print(content)
Expected Output:
b'Hello, World!\nAppending this line.'

14. Write to a Binary File


Code:
with open("file3.bin", "wb") as f:
f.write(b"Binary data")
Expected Output: (File created)
Content of file3.bin: Binary data

15. Read from a Binary File


Code:
with open("file3.bin", "rb") as f:
content = f.read()
print(content)

Expected Output:
b'Binary data'

16. Create a Directory


Code:
os.mkdir("new_directory")

Expected Output: (Directory created)


new_directory created.

17. List Files in a Directory


Code:

import os
files = os.listdir("new_directory")
print(files)

Expected Output:
[] (Initially empty since no files have been added yet.)

18. Write to a File in a New Directory


Code:
with open("new_directory/file_in_new_dir.txt", "w") as f:
f.write("This is a file in a new directory.")

Expected Output: (File created in the new directory)


Content of file_in_new_dir.txt: This is a file in a new directory.

19. Read from a File in a New Directory


Code:
with open("new_directory/file_in_new_dir.txt", "r") as f:
content = f.read()
print(content)

Expected Output:
This is a file in a new directory.

20. Remove a Directory


Code:
os.rmdir("new_directory")
Expected Output: (Directory removed)
new_directory removed.

21. Write JSON to a File


Code:
import json

data = {"name": "Alice", "age": 30}


with open("data.json", "w") as f:
json.dump(data, f)

Expected Output: (File created with JSON content)


Content of data.json: {"name": "Alice", "age": 30}

22. Read JSON from a File


Code:
with open("data.json", "r") as f:
data = json.load(f)
print(data)

Expected Output:
{'name': 'Alice', 'age': 30}

23. Write CSV to a File


Code:
import csv

data = [["Name", "Age"], ["Alice", 30], ["Bob", 25]]


with open("data.csv", "w", newline='') as f:
writer = csv.writer(f)
writer.writerows(data)

Expected Output: (File created with CSV content)


Content of data.csv:
Name,Age
Alice,30
Bob,25

24. Read CSV from a File


Code:
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)

Expected Output:
['Name', 'Age']
['Alice', '30']
['Bob', '25']

25. Write to a File with Exception Handling


Code:
try:
with open("file4.txt", "w") as f:
f.write("Writing with exception handling.")
except Exception as e:
print(f"An error occurred: {e}")

Expected Output: (File created)


Content of file4.txt: Writing with exception handling.

26. Read a File with Exception Handling


Code:
try:
with open("file4.txt", "r") as f:
content = f.read()
print(content)
except FileNotFoundError:
print("File not found.")
Expected Output:
Writing with exception handling.

27. Write a File with a Custom Function


Code:
def write_to_file(filename, content):
with open(filename, "w") as f:
f.write(content)

write_to_file("file5.txt", "This is a custom function to write to a file.")


Expected Output: (File created)
Content of file5.txt: This is a custom function to write to a file.

28. Read a File with a Custom Function


Code:
def read_from_file(filename):
with open(filename, "r") as f:
return f.read()

print(read_from_file("file5.txt"))
Expected Output:
This is a custom function to write to a file.

29. Write a File with User Input


Code:
user_input = input("Enter some text to write to a file: ")
with open("user_input.txt", "w") as f:
f.write(user_input)
Expected Output: (File created with user input)
Content of user_input.txt: (whatever the user entered)

You might also like