[英]Updating a CSV file in Python
I am trying to update a csv file, https://www.kaggle.com/carolzhangdc/imdb-5000-movie-dataset
.我正在尝试更新 csv 文件
https://www.kaggle.com/carolzhangdc/imdb-5000-movie-dataset
。
At the end of this csv file I am trying to append a new url to the image of the movie.在这个 csv 文件的末尾,我正在尝试将 append 一个新的 url 转换为电影的图像。
my code is below我的代码在下面
import csv
from bs4 import BeautifulSoup
import urllib2
with open('movie_metadata.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
print('Column names are {}'.format(", ".join(row)))
row[-1] = "movie_links"
line_count += 1
else:
imdb_link = row[17]
soup = BeautifulSoup(urllib2.urlopen(imdb_link).read(), features="html.parser")
link = soup.find_all('div', {'class': 'poster'})
if link:
row[-1] = link[0].find('img')['src']
line_count += 1
print('Processed {} lines.'.format(line_count))
I am creating a new row at row[-1]
and trying to update the csv file if link:
我在
row[-1]
创建一个新行并尝试更新 csv 文件if link:
But it's not updating my csv file at all, it stays the same after I run my code.但它根本没有更新我的 csv 文件,在我运行我的代码后它保持不变。
Do you realize you overwrite the last element in the array row
?您是否意识到您覆盖了数组
row
中的最后一个元素? You should append()
instead of changing [-1]
.您应该
append()
而不是更改[-1]
。 Try:尝试:
row.append("movie_links")
instead of row[-1] = "movie_links"
row.append("movie_links")
而不是row[-1] = "movie_links"
and和
row.append(link[0].find('img')['src'])
instead of row[-1] = link[0].find('img')['src']
. row.append(link[0].find('img')['src'])
而不是row[-1] = link[0].find('img')['src']
。
Then, to actually write the CSV file, use csv.writer
with the new row (documentation here: https://docs.python.org/3/library/csv.html ). Then, to actually write the CSV file, use
csv.writer
with the new row (documentation here: https://docs.python.org/3/library/csv.html ).
Note, row + ["movie links"]
for the first one is another way to append.注意,第一个的
row + ["movie links"]
是 append 的另一种方式。 Using [-1]
Overwrites the last element instead of appending.使用
[-1]
覆盖最后一个元素而不是追加。 Let me know if you want me to code you the csv writing portion.如果你想让我给你编码 csv 写作部分,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.