[英]Copy specific rows from one csv to another using python
我有一個帶有行索引號的變量,我想從一個CSV文件中獲取這些行並將這些行寫入一個新行。
我想要復制的CSV文件如下所示:
sdkgsk; 74785797; hdfgsdgfjss
asdjkhfgsdkjg; 9857349834; jsdhfg
skhgf; 76578346534; jhfgsdjhgdf
sdifl; 56975654; kjdjh
afhkddf; 439587349346; hsfd
kdgfdkj; 983496; hioas
oish; 89468468; jhfdsgsdf
jksdfjhksdfjk; 8968; jkfdsjhksd
我曾嘗試過多種方法,但這是最后一項:
row_index = [2,4,6]
with open('test.csv', 'r') as f,open('out.csv', 'w') as f_out:
reader = csv.reader(f)
writer = csv.writer(f_out)
lines = list(reader)
for row in lines:
writer.writerow(row[row_index])
我希望生成一個名為'out.csv'的新文件,它包含'test.csv'中的第2,4和6行
相反,我收到此錯誤消息:“列表索引必須是整數或切片,而不是列表”
問題出在這一行:
writer.writerow(row[row_index])
row_index
是一個列表,您不能將整數row
( row
)與另一個列表索引。 這正是python解釋器嘗試用這個錯誤消息告訴你的: list indices must be integers or slices, not list
你可以做的是使用list comprehension來創建基於row_index
列表的new_row
:
for row in lines:
new_row = [row[index] for index in row_index]
writer.writerow(new_row)
編輯:我錯過了另一個問題。根據你的代碼,我認為你想要從每一行重寫第2,4和6列,但你真正想要索引的是行,而不是列。 所以你想要重寫完整的2,4和6行。在這種情況下,你可以再次使用列表理解。
with open('test.csv', 'r') as f,open('out.csv', 'w') as f_out:
reader = csv.reader(f)
writer = csv.writer(f_out)
lines = list(reader)
new_rows = [lines[index] for index in row_index]
writer.writerows(new_rows)
並再次list index out of range
錯誤消息告訴您到底出了什么問題。 請嘗試下次仔細閱讀和解釋錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.