用Python先生成一个StrInts.txt文件(随机正负的500个0到9999的随机整数,以任意形式写到文件),个位数为奇数位,十位数为偶数位。编写程序读取该文件并提取出其中所有的整数,然后将这些整数中偶数位上全部都为奇数列,右对齐,左补空格。的整数保存到当前路径的 ResultInts . txt 文件中去,保存时每行3个数,每个数占8列,右对齐,左补空格
时间: 2023-10-22 08:04:55 浏览: 42
生成StrInts.txt文件的代码如下:
```python
import random
with open("StrInts.txt", "w") as f:
for i in range(500):
num = random.randint(-9999, 9999)
if num >= 0:
s = str(num).zfill(5)
else:
s = "-" + str(abs(num)).zfill(4)
if int(s[3]) % 2 != 0 and int(s[2]) % 2 == 0:
f.write(s + "\n")
```
读取StrInts.txt文件并提取出符合条件的整数,并保存到ResultInts.txt文件中的代码如下:
```python
with open("StrInts.txt", "r") as f1, open("ResultInts.txt", "w") as f2:
res = []
for line in f1:
num = int(line.strip())
if all(int(s) % 2 != 0 for s in line.strip()[::2]):
res.append(line.strip().rjust(8))
for i in range(0, len(res), 3):
f2.write(" ".join(res[i:i+3]).rjust(26) + "\n")
```
解释一下代码:
第一个代码块使用random模块生成了500个随机整数,并将符合条件的整数写入到StrInts.txt文件中。
第二个代码块使用了两个文件句柄,一个用来读取StrInts.txt文件,一个用来写入ResultInts.txt文件。代码首先定义了一个空列表res,用来存放符合条件的整数。然后对于读取到的每一行,如果这个整数的奇数位上都是奇数,偶数位上都是偶数(即满足题目要求),就将其加入到res列表中。最后,将res列表中的整数按照题目要求写入到ResultInts.txt文件中。具体地,我们每次将3个整数拼接成一行,每个整数占8列,右对齐,左补空格,每行总共占26列。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.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)
![](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)