Python Code Demonstrating Basic File Operations: open
, read
, write
The following Python code demonstrates basic file operations such as opening, reading, and writing to a file.
Example: Basic File Operations
# Writing to a file with open("test.txt", "wt") as out_file: out_file.write("This text will be written to the file.\nCan you see it now?") # Reading from a file with open("test.txt", "rt") as in_file: text = in_file.read() # Print the content read from the file print(text)
Sample Output:
This text will be written to the file. Can you see it now?
In this example, the script writes the text "This text will be written to the file.\nCan you see it now?"
into a file named test.txt
. It then reads the content of the file and prints it to the console.