简体   繁体   English

从 csv 文件读取、编辑和写入数据

[英]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)

Here is my code.这是我的代码。 I am able to read data from a csv file on my desktop and rewrite the same data to another csv file on designated location.我能够从桌面上的 csv 文件中读取数据,并将相同的数据重写到指定位置的另一个 csv 文件中。 But my question is, while i am re-writing the data, i want to edit/change only first columns where my titles are.但我的问题是,当我重写数据时,我只想编辑/更改我的标题所在的第一列。 I want to rename the title names and add new columns(only titles)我想重命名标题名称并添加新列(仅标题)

This is my example CSV where I want to read and take all data as it is这是我的示例 CSV ,我想在其中读取并获取所有数据

在此处输入图像描述

a) I would like to keep the same data: From A to K (including K column) check the example image above a)我想保留相同的数据:从 A 到 K(包括 K 列)检查上面的示例图像

b) I want to modify only column titles on Column L and M (at first they were Person L and Person M). b) 我只想修改 L 列和 M 列上的列标题(起初它们是 Person L 和 Person M)。 In my edited file i want to change them to New Title L, New Title M在我编辑的文件中,我想将它们更改为新标题 L、新标题 M

c) After the M column, i want to add extra column title names till Column T (New Title N, New Title O, New Title P, New Title Q, New Title R, New Title S, New Title T) c)在 M 列之后,我想在 T 列之前添加额外的列标题名称(新标题 N、新标题 O、新标题 P、新标题 Q、新标题 R、新标题 S、新标题 T)

At the end my desired file need to look like this最后我想要的文件需要看起来像这样在此处输入图像描述

So i want to read, meanwhile edit my csv and store edited new file on my desktop/etc place.所以我想阅读,同时编辑我的 csv 并将编辑后的新文件存储在我的桌面/等位置。 So far i can only copy paste same data with python and couldn't edit or add new titles.到目前为止,我只能使用 python 复制粘贴相同的数据,并且无法编辑或添加新标题。 Thanks a lot.非常感谢。 Sorry for my inconvenience, i am a newbie on programming:)很抱歉给我带来不便,我是编程新手:)

You have to change modify in this loop.您必须在此循环中更改修改。

   for line in csv_reader:
        new_line = modify(line)
        csv_writer.writerow(new_line)

This will work because here the line is a list of strings.这将起作用,因为这里的line是字符串列表。 So if your string is in the first column then it can be accessed using line[0] .因此,如果您的字符串位于第一列,则可以使用line[0]访问它。 This is for every row.这适用于每一行。 To get the current row index, enumerate can be used.要获取当前行索引,可以使用enumerate Then the code becomes然后代码变成

   for row_index, line in enumerate(csv_reader):
        new_line = modify(row_index, line)
        csv_writer.writerow(new_line)

Note I added a modify function.注意我添加了一个modify function。 Now If we implement the modify function with your logic then the problem can be solved easily.现在如果我们用你的逻辑实现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

defining a function to add 7 more headers on CSV file定义一个 function 以在 CSV 文件上添加 7 个以上的标题

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

opening the file which we give the exact directory and storing it as a variable "csv_file"打开我们给出确切目录的文件并将其存储为变量“csv_file”

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM