Python provides functions to work with files. You can read from and write to files using built-in functions like open()
, read()
, and write()
.
To open a file, use the open()
function, which takes the file name and the mode in which you want to open the file (e.g., 'r'
for reading, 'w'
for writing):
file = open("example.txt", "w")
file.write("Hello, world!")
file.close()
This code opens (or creates) a file called example.txt
, writes "Hello, world!" to it, and then closes the file.
To read the contents of a file, use the read()
function:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
This reads the content of the file and prints it.
Create a program that writes your name to a file and then reads and prints the content of the file.
Answers: Use open()
to open a file. Use write()
to write content to a file.