使用 writelines 将 list_s 写写入c.txt
时间: 2024-03-25 18:35:35 浏览: 10
可以使用以下代码将列表 `list_s` 写入文件 `c.txt` 中:
```python
list_s = ['Hello', 'world', '!', 'How', 'are', 'you', '?']
with open('c.txt', 'w') as f:
f.writelines([s + '\n' for s in list_s])
```
这里使用了列表推导式将列表中的每个字符串加上换行符 `\n`,然后使用 `writelines` 方法将整个列表写入文件。注意,`writelines` 方法不会自动添加行尾符,需要手动添加。
相关问题
用Python将deepfashion数据集的list_category_img.txt变成CSV文件
可以使用Python中的csv模块将deepfashion数据集的list_category_img.txt文件转换为CSV文件。
以下是示例代码:
```python
import csv
# 打开list_category_img.txt文件
with open('list_category_img.txt', 'r') as file:
lines = file.readlines()
# 分割每一行,将数据存储到列表中
data = []
for line in lines:
line = line.strip().split()
filename = line[0]
category_id = line[1]
data.append([filename, category_id])
# 将数据写入CSV文件
with open('list_category_img.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
```
这段代码会将list_category_img.txt文件中的数据读入到一个列表中,然后将列表中的数据写入到list_category_img.csv文件中。你可以根据自己的需要修改文件名和路径。
用Python将deepfashion数据集的list_category_cloth.txt变成CSV文件
可以使用Python中的csv模块将deepfashion数据集的list_category_cloth.txt文件转换为CSV文件。
以下是示例代码:
```python
import csv
# 打开list_category_cloth.txt文件
with open('list_category_cloth.txt', 'r') as file:
lines = file.readlines()
# 分割每一行,将数据存储到列表中
data = []
for line in lines:
line = line.strip().split()
category_id = line[0]
category_name = line[1]
data.append([category_id, category_name])
# 将数据写入CSV文件
with open('list_category_cloth.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
```
这段代码会将list_category_cloth.txt文件中的数据读入到一个列表中,然后将列表中的数据写入到list_category_cloth.csv文件中。你可以根据自己的需要修改文件名和路径。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)