-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileHandling-10mins.py
More file actions
46 lines (31 loc) · 1.77 KB
/
FileHandling-10mins.py
File metadata and controls
46 lines (31 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# "Python allows you to read, write, and update files easily.
# This is useful for saving data or working with external files."
# Key Methods:
# 1. open(file, mode): Opens a file and returns a file object.
# 'r': Read
# 'w': Write (overwrites existing content)
# 'a': Append
# read() and write() - Read or write data.
# Always close the file with close() or use with.
# Example Code – Writing to a File:
with open("example.txt", "w") as file: # Open the file "example.txt" in write mode
file.write("Hello, World!\n") # Write "Hello, World!" followed by a newline to the file
file.write("Python is fun!") # Write "Python is fun!" to the file
# Example Code – Reading from a File:
with open("example.txt", "r") as file: # Open the file "example.txt" in read mode
content = file.read() # Read the entire content of the file
print(content) # Print the content of the file
# Output:
print("Hello, World!") # Print "Hello, World!" to the console
print("Python is fun!") # Print "Python is fun!" to the console
# Student Activity:
# Write a program that asks the user for their name and saves it to a file.
# Read the file and display the saved name.
with open("example.txt", "w") as file: # Open the file "example.txt" in write mode
file.write("Hello, World!\n") # Write "Hello, World!" followed by a newline to the file
file.write("Python is fun!") # Write "Python is fun!" to the file
with open("example.txt", "r") as file: # Open the file "example.txt" in read mode
content = file.read() # Read the entire content of the file
print(content) # Print the content of the file
print("Hello, World!") # Print "Hello, World!" to the console
print("Python is fun!") # Print "Python is fun!" to the console