用Python将deepfashion数据集的list_bbox.txt变成CSV文件,不使用pandas
时间: 2024-03-24 07:40:58 浏览: 112
可以使用Python内置的csv模块来实现。
假设你已经读取了`list_bbox.txt`文件并将其存储为一个列表,每个元素都是一个包含多个属性的字典,可以按照以下步骤将其转换为CSV文件:
1. 打开一个新的CSV文件并获取一个写入器对象:
```python
import csv
with open('list_bbox.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
```
2. 写入CSV文件的标题行:
```python
headers = ['image_name', 'x_1', 'y_1', 'x_2', 'y_2']
writer.writerow(headers)
```
3. 遍历列表中的每个字典,并将属性值写入CSV文件中:
```python
for item in list_bbox:
row = [item['image_name'], item['x_1'], item['y_1'], item['x_2'], item['y_2']]
writer.writerow(row)
```
4. 关闭CSV文件:
```python
csvfile.close()
```
完整代码如下:
```python
import csv
with open('list_bbox.txt', 'r') as f:
lines = f.readlines()[2:] # 去除前两行
list_bbox = []
for line in lines:
line = line.strip().split()
item = {
'image_name': line[0],
'x_1': line[1],
'y_1': line[2],
'x_2': line[3],
'y_2': line[4]
}
list_bbox.append(item)
with open('list_bbox.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
headers = ['image_name', 'x_1', 'y_1', 'x_2', 'y_2']
writer.writerow(headers)
for item in list_bbox:
row = [item['image_name'], item['x_1'], item['y_1'], item['x_2'], item['y_2']]
writer.writerow(row)
csvfile.close()
```
阅读全文