随机生成包含 100 个 1-1000 的整数的列表,写入到磁盘文件 A 中;读出 A 文件的内容,选出其中能被5和9同时整除的数, 输出到一个新文件 B 中。
时间: 2024-03-11 09:48:26 浏览: 17
生成包含 100 个 1-1000 的整数的列表,并写入到磁盘文件A中的Python代码如下:
```python
import random
# 生成包含100个1-1000的整数的列表
nums = [random.randint(1, 1000) for _ in range(100)]
# 写入到磁盘文件A中
with open('A.txt', 'w') as f:
f.write('\n'.join(map(str, nums)))
```
读出A文件的内容,选出其中能被5和9同时整除的数,并输出到一个新文件B中的Python代码如下:
```python
# 读取A文件的内容
with open('A.txt', 'r') as f:
nums = list(map(int, f.read().split()))
# 选出能被5和9同时整除的数
nums_selected = [num for num in nums if num % 5 == 0 and num % 9 == 0]
# 输出到新文件B中
with open('B.txt', 'w') as f:
f.write('\n'.join(map(str, nums_selected)))
```
以上代码会在当前目录下生成两个文件A.txt和B.txt。其中A.txt包含100个1-1000的随机整数,每个整数占一行;B.txt包含能被5和9同时整除的数,每个整数占一行。
相关问题
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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)