![](/img/trans.png)
[英]Python - Reading in data from csv and then writing to new csv with data and file number from loop
[英]Reading, editing and writing data from a csv file
import csv
with open( "example.csv" , "r") as csv_file:
csv_reader = csv.reader(csv_file)
with open("edited.csv", "w", newline='') as new_file:
csv_writer = csv.writer(new_file)
for line in csv_reader:
csv_writer.writerow(line)
這是我的代碼。 我能夠從桌面上的 csv 文件中讀取數據,並將相同的數據重寫到指定位置的另一個 csv 文件中。 但我的問題是,當我重寫數據時,我只想編輯/更改我的標題所在的第一列。 我想重命名標題名稱並添加新列(僅標題)
這是我的示例 CSV ,我想在其中讀取並獲取所有數據
a)我想保留相同的數據:從 A 到 K(包括 K 列)檢查上面的示例圖像
b) 我只想修改 L 列和 M 列上的列標題(起初它們是 Person L 和 Person M)。 在我編輯的文件中,我想將它們更改為新標題 L、新標題 M
c)在 M 列之后,我想在 T 列之前添加額外的列標題名稱(新標題 N、新標題 O、新標題 P、新標題 Q、新標題 R、新標題 S、新標題 T)
所以我想閱讀,同時編輯我的 csv 並將編輯后的新文件存儲在我的桌面/等位置。 到目前為止,我只能使用 python 復制粘貼相同的數據,並且無法編輯或添加新標題。 非常感謝。 很抱歉給我帶來不便,我是編程新手:)
您必須在此循環中更改修改。
for line in csv_reader:
new_line = modify(line)
csv_writer.writerow(new_line)
這將起作用,因為這里的line
是字符串列表。 因此,如果您的字符串位於第一列,則可以使用line[0]
訪問它。 這適用於每一行。 要獲取當前行索引,可以使用enumerate
。 然后代碼變成
for row_index, line in enumerate(csv_reader):
new_line = modify(row_index, line)
csv_writer.writerow(new_line)
注意我添加了一個modify
function。 現在如果我們用你的邏輯實現modify
function 那么問題就可以輕松解決了。
def modify(row_index, line):
title_names = ["N", "O", "P", "Q", "R", "S", "T"]
if row_index == 0:
line[11] = "New Title L"
line[12] = "New Title M"
# Also add 7 more columns
if row_index == 0:
line.extend(["New Title %s" % n for n in title_names])
else:
# Add empty columns to make sure column size is always same.
line.extend([""] * 7)
return line
import csv
def modify (row_index, line):
if row_index == 0:
line.extend(["New Title L","New Title M",
"New Title N", "New Title O", "New Title P", "New Title Q", "New Title R", "New Title S", "New Title T"])
else:
line.extend([""] * 7)
return line
with open("C:/Users/LOGIN/Desktop/Example1.csv" , "r") as csv_file:
csv_reader = csv.reader(csv_file)
# and opening second file with writer function on directory we designated to. This will write everything line by line from the file we opened above. In addtion, with "modify" function it adds 7 more lines that we defined. New CSV file will be on the desktop.
with open("C:/Users/LOGIN/Desktop/new_edited_file.csv", "w", newline='') as new_file:
csv_writer = csv.writer(new_file)
for row_index, line in enumerate(csv_reader):
new_line = modify(row_index, line)
csv_writer.writerow(new_line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.