Objectives: To practice File and text input output concept 1. (Process scores in a text file) Suppose a text file contains an unspecified number of scores separated by spaces. Write a program that prompts the user to enter the file, reads the scores from the file, and displays their total and average. 2. (Write/read data) Write a program to create a file named Lab07_02.txt if it does not exist. Write 100 integers created randomly into the file using text I/O. Integers are separated by spaces in the file. Read the data back from the file and display the data in increasing order.
时间: 2023-12-03 18:42:55 浏览: 127
1. Here's the code to process scores in a text file:
```python
filename = input("Enter the file name: ")
try:
with open(filename, "r") as file:
scores = [int(score) for score in file.read().split()]
total = sum(scores)
average = total / len(scores)
print("Total: ", total)
print("Average: ", average)
except FileNotFoundError:
print("File not found.")
```
2. Here's the code to write/read data:
```python
import random
filename = "Lab07_02.txt"
try:
with open(filename, "x") as file:
data = [str(random.randint(1, 100)) for i in range(100)]
file.write(" ".join(data))
except FileExistsError:
pass
try:
with open(filename, "r") as file:
data = [int(num) for num in file.read().split()]
data.sort()
print(data)
except FileNotFoundError:
print("File not found.")
```
阅读全文