Responsive Navbar with Google Search
☰ Menu
Home
Python
LaTeX
GNUPlot
Arduino
Feedback
Contact Us
Introduction to Python: I/O Operation
Introduction to Python
Print Function
Variable and Data Types
Mathematical Operations
Conditionals (if, elif, else)
For Loop
While Loop
User Defined Function
Module math and cmath
I/O Operation
I/O Operation: Program 1
'''write text to file''' with open("example.txt", "w") as file: file.write("Hello, User! This is a file write example.") '''read text from file''' with open("example.txt", "r") as file: content = file.read() print(content) '''Append text to file''' with open("example.txt", "a") as file: file.write("\nThis is an appended line.") '''read file after append''' with open("example.txt", "r") as file: content = file.read() print(content)
Run Code
Output 1
I/O Operation: Program 2
# Writing numbers to a file numbers = [1, 2, 3, 4, 5,6,7,8] with open('data.txt', 'w') as file: for number in numbers: file.write(str(number) + "\n") # Reading numbers from the file with open('data.txt', 'r') as file: content = [int(line.strip()) for line in file] print(content)
Run Code
Output 2
I/O Operation: Program 3
# Writing structured data to a file data = [["ID", "Name", "Score"], [1, "ABC", 85], [2, "DEF", 90], [3, "GHI", 78]] with open('data.txt', 'w') as file: for row in data: file.write(" | ".join(map(str, row)) + "\n") # Reading structured data from the file with open('data.txt', 'r') as file: content = file.read() print(content)
Run Code
Output 3