python如何将列表的str写入文件中
时间: 2023-12-03 19:03:40 浏览: 32
可以使用Python中的“写入模式”打开文件并写入列表。以下是示例代码:
```
my_list = ['apple', 'banana', 'orange']
with open('myfile.txt', 'w') as f:
for item in my_list:
f.write("%s\n" % item)
```
这将把列表中的每个元素依次写入名为“myfile.txt”的文件中,每个元素占一行。
相关问题
python将列表写入文件
可以通过以下步骤将Python列表写入文件:
1. 打开文件:使用Python内置的`open()`函数以写入模式打开文件。例如,`file = open('example.txt', 'w')`将创建一个名为`example.txt`的文件并以写入模式打开它。
2. 将列表写入文件:使用`write()`函数将列表写入文件。首先将列表转换为字符串形式,然后将其写入文件。例如,`file.write(str(my_list))`将列表`my_list`以字符串形式写入文件。
3. 关闭文件:使用`close()`函数关闭文件以确保文件被保存并释放资源。例如,`file.close()`将关闭文件。
下面是一个示例代码,将一个包含5个整数的列表写入名为`example.txt`的文件中:
```python
my_list = [1, 2, 3, 4, 5]
with open('example.txt', 'w') as file:
file.write(str(my_list))
```
在上面的代码中,我们使用了`with`语句打开文件,这样在代码块执行完毕后会自动关闭文件。然后将列表`my_list`以字符串形式写入文件`example.txt`中。最后,使用`close()`函数显式地关闭文件。
python中将列表写入文件
以下是两种将列表写入文件的方法:
方法一:使用文件操作符将列表写入txt文件中
```python
a=[['1','9'],['2','5'],['3','3'],['2','4'],['4','3'],['1','8'],['1','9']]
t=''
with open ('N_a.txt','w') as q:
for i in a:
for e in range(len(a[0])):
t=t+str(i[e])+' '
q.write(t.strip(' '))
q.write('\n')
t=''
```
方法二:使用text_save函数将列表写入txt文件中
```python
# 将操作码保存为txt文件
def text_save(filename, data):
# filename为写入txt文件的路径,data为要写入数据列表.
file = open(filename, 'a')
for i in range(len(data)):
s = str(data[i]).replace('[', '').replace(']', '')#去除[],这两行按数据不同,可以选择
s = s.replace("'", '').replace(',', '') + '\n' #去除单引号,逗号,每行末尾追加换行符
file.write(s)
file.close()
print("保存文件成功")
ops = [['i','love','china'],['happy','birthday']]
text_save('ops.txt', ops)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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_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)