csv 如何将jpg转换为jpeg

b4lqfgs4  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(174)

我有一个python脚本,将采取csv文件,其中包含所有的图像在文件格式:

Alfa,Beta,Charlie,Delta,Echo
A1,B1,C1,D1,AX1.jpg
A2,B2,C2,D2,BX1.jpg
A3,B3,C3,D3,CX1.jpg
A4,B4,C4,D4,BX1.jpg
A4,B4,C4,D4,CX1.jpg
A4,B4,C4,D4,AX1.jpg

脚本:

import csv

with open('sample.csv') as csv_file:
    column_numbers = 'Echo'
    reader = csv.DictReader(csv_file)
    for row in reader:
            for ky in row[column_numbers] translate from jpg to jpeg

因此csv文件将如下所示:

Alfa,Beta,Charlie,Delta,Echo
    A1,B1,C1,D1,AX1.jpeg
    A2,B2,C2,D2,BX1.jpeg
    A3,B3,C3,D3,CX1.jpeg
    A4,B4,C4,D4,BX1.jpeg
    A4,B4,C4,D4,CX1.jpeg
    A4,B4,C4,D4,AX1.jpeg
cczfrluj

cczfrluj1#

在这个特殊的例子中,它是csv并不重要,因为您只是希望对文本文件执行搜索和替换。
正如@Tim Roberts所评论的,这可以使用命令行工具(sed -e s/jpg/jpeg/ < sample.csv)来完成,但无论如何,让我们用Python来完成它......
试试这个可运行的例子!

#!/usr/bin/env python
# to set up let's recreate the file
with open("sample.csv",'w') as f:
    f.write("""
Alfa,Beta,Charlie,Delta,Echo
A1,B1,C1,D1,AX1.jpg
A2,B2,C2,D2,BX1.jpg
A3,B3,C3,D3,CX1.jpg
A4,B4,C4,D4,BX1.jpg
A4,B4,C4,D4,CX1.jpg
A4,B4,C4,D4,AX1.jpg
""")

# now read the file into a string
with open('sample.csv') as csv_file:
    full_text = csv_file.read()
    
# correct the string
new_full_text = full_text.replace(".jpg", ".jpeg")

# overwrite the original file
with open('sample.csv', 'w') as csv_file:
    csv_file.write(new_full_text)
    
# check the output

desired_output = """
Alfa,Beta,Charlie,Delta,Echo
A1,B1,C1,D1,AX1.jpeg
A2,B2,C2,D2,BX1.jpeg
A3,B3,C3,D3,CX1.jpeg
A4,B4,C4,D4,BX1.jpeg
A4,B4,C4,D4,CX1.jpeg
A4,B4,C4,D4,AX1.jpeg
"""
with open('sample.csv') as csv_file:
    check_full_text = csv_file.read()

print(check_full_text == desired_output)

check_full_text
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

相关问题