利用程序生成一个列表["11","22","33","44","55","66","77","88","99"],然后将其写入文件list,txt,再用print()函数输出python
时间: 2023-09-02 21:05:37 浏览: 68
代码如下:
```
num_list = ["11","22","33","44","55","66","77","88","99"]
# 将列表写入文件
with open("list.txt", "w") as f:
for num in num_list:
f.write(num + '\n')
# 从文件中读取并输出内容
with open("list.txt", "r") as f:
for line in f:
print(line.strip())
```
这段代码首先定义了一个包含数字字符串的列表。然后用"with open"语句来打开一个名为"list.txt"的新文件,并以写入模式("w")打开。通过循环遍历数字列表,并使用 "\n" 在每行末尾添加一个换行符,然后将每行写入文件。最后再一次使用"with open"语句打开文件,这次以读取模式("r")打开,并使用循环遍历文件中的每行,使用strip()方法删除行尾的换行符,并将每行输出到控制台。
相关问题
编写一个程序生成列表[11,22,33,44,55,66,77,88,99],将其写入文件python1.txt中,然后从文件中读出该列表,用print()函数输出
好的,现在我将编写一个程序来生成所需的列表并将其写入python1.txt文件中:
```
my_list = [11,22,33,44,55,66,77,88,99]
with open('python1.txt', 'w') as file:
for item in my_list:
file.write("%s\n" % item)
```
接下来,我将从文件中读取该列表并使用print()函数打印它:
```
with open('python1.txt', 'r') as file:
my_list = [int(line.strip()) for line in file]
print(my_list)
```
输出将是:
```
[11, 22, 33, 44, 55, 66, 77, 88, 99]
```
用python编写一个程序生成列表[11,22,33,44,55,66,77,88,99],将其写入文件python1.txt中,然后从文件中读出该列表,用print()函数输出。
好的,以下是代码:
```python
# 生成列表并写入文件
my_list = [11,22,33,44,55,66,77,88,99]
with open('python1.txt', 'w') as f:
for num in my_list:
f.write(str(num) + '\n')
# 从文件中读出列表并输出
with open('python1.txt', 'r') as f:
my_list2 = []
for line in f.readlines():
my_list2.append(int(line.strip()))
print(my_list2)
```
这段代码会将列表写入文件`python1.txt`中,并且用`print()`函数输出从文件中读出来的列表。
相关推荐
![](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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![sb3](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)