Reputation: 83
I have a python script that will take the csv file, that contains all of the images in the file format:
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
script:
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
So that the csv file will look like this:
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
Upvotes: 0
Views: 112
Reputation: 651
In this particular example, the fact that it is a csv does not matter since you are simply looking to do a search and replace on the text file.
As @Tim Roberts commented, this can be done using command line tools (sed -e s/jpg/jpeg/ < sample.csv
), but let's do it in Python anyway...
Try this runnable example!
#!/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>
Upvotes: 1