随机生成包含 100 个 1-1000 的整数的列表,写入到磁盘文件 A 中;读出 A 文件的内容,选出其中能被5和9同时整除的数, 输出到一个新文件 B 中。
时间: 2024-03-11 16:48:04 浏览: 4
好的,我明白了。以下是 Python 代码实现:
```python
import random
# 随机生成包含 100 个 1-1000 的整数的列表
num_list = [random.randint(1, 1000) for _ in range(100)]
# 写入到磁盘文件 A 中
with open('A.txt', 'w') as f:
for num in num_list:
f.write(str(num) + '\n')
# 读出 A 文件的内容,选出其中能被5和9同时整除的数, 输出到一个新文件 B 中
with open('A.txt', 'r') as f:
with open('B.txt', 'w') as f2:
for line in f:
num = int(line.strip())
if num % 5 == 0 and num % 9 == 0:
f2.write(str(num) + '\n')
```
以上代码中,我们首先使用 `random.randint` 函数生成了一个包含 100 个 1-1000 的整数的列表 `num_list`,然后将其写入到文件 A 中。接着,我们使用 `with open` 语句打开 A 文件,逐行读取其中的内容,判断能否同时被 5 和 9 整除,将符合条件的数写入到文件 B 中。注意,我们在读取文件时使用了 `strip()` 函数去掉了每行末尾的换行符。
相关问题
8. 随机生成包含 100 个 1-1000 的整数的列表,写入到磁盘文件 A 中;读出 A 文件的内容,选出其中能被5和9同时整除的数, 输出到一个新文件 B 中。
生成包含 100 个 1-1000 的随机整数列表:
```python
import random
a_list = [random.randint(1, 1000) for _ in range(100)]
```
写入到磁盘文件 A 中:
```python
with open("A.txt", "w") as f:
for num in a_list:
f.write(str(num) + "\n")
```
读取 A 文件的内容,并选出其中能被5和9同时整除的数,写入到 B 文件中:
```python
with open("A.txt", "r") as f, open("B.txt", "w") as g:
for line in f:
num = int(line.strip())
if num % 5 == 0 and num % 9 == 0:
g.write(str(num) + "\n")
```
完整代码如下:
```python
import random
a_list = [random.randint(1, 1000) for _ in range(100)]
with open("A.txt", "w") as f:
for num in a_list:
f.write(str(num) + "\n")
with open("A.txt", "r") as f, open("B.txt", "w") as g:
for line in f:
num = int(line.strip())
if num % 5 == 0 and num % 9 == 0:
g.write(str(num) + "\n")
```
注意:如果在读取 A 文件内容时,出现无法转换为整数的行,程序会报 ValueError 的错误。可以添加 try-except 语句来处理这种情况。
随机生成100-999的1000个随机整数,每个整数占一行,写入d:\text.txt文件中
以下是Python代码实现:
```python
import random
# 生成随机整数并写入文件
with open('d:\\text.txt', 'w') as file:
for i in range(1000):
num = random.randint(100, 999)
file.write(str(num) + '\n')
```
解释一下代码:
- `import random`:导入Python内置的随机数模块。
- `with open('d:\\text.txt', 'w') as file:`:打开文件,如果文件不存在则创建,以写入模式打开,使用`with`语句可以自动关闭文件。
- `for i in range(1000):`:循环1000次,每次生成一个随机整数并写入文件。
- `num = random.randint(100, 999)`:生成100-999之间的随机整数。
- `file.write(str(num) + '\n')`:将随机整数转换为字符串并写入文件,每个整数占一行。`'\n'`表示换行符。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)