如何在 Python 中向旧的 CSV 文件追加新行?

发布于 2024-08-23 15:50:56 字数 134 浏览 6 评论 0原文

我正在尝试向旧的 CSV 文件添加新行。基本上,每次运行 Python 脚本时它都会更新。

现在,我将旧的 CSV 行值存储在列表中,然后删除 CSV 文件并使用新的列表值再次创建它。

我想知道是否有更好的方法可以做到这一点。

I am trying to add a new row to my old CSV file. Basically, it gets updated each time I run the Python script.

Right now I am storing the old CSV rows values in a list and then deleting the CSV file and creating it again with the new list value.

I wanted to know are there any better ways of doing this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

錯遇了你 2024-08-30 15:50:57
with open('document.csv','a') as fd:
    fd.write(myCsvRow)

使用 'a' 参数打开文件允许您追加到文件末尾,而不是简单地覆盖现有内容。尝试一下。

with open('document.csv','a') as fd:
    fd.write(myCsvRow)

Opening a file with the 'a' parameter allows you to append to the end of the file instead of simply overwriting the existing content. Try that.

暮年慕年 2024-08-30 15:50:57

我更喜欢使用 csv 标准库中的模块和 with 语句以避免让文件保持打开状态。

关键点是在打开文件时使用 'a' 进行追加。

import csv   
fields=['first','second','third']
with open(r'name', 'a') as f:
    writer = csv.writer(f)
    writer.writerow(fields)

如果您使用的是 Python 2.7,您可能会在 Windows 中遇到多余的新行。您可以尝试使用 'ab' 而不是 'a' 来避免它们,但这会导致您TypeError:需要类似字节的对象,而不是 python 和 CSV 中的“str”。正如 Natacha 建议的那样,添加 newline='' 会导致您 Python 2 和 3 之间向后不兼容

I prefer this solution using the csv module from the standard library and the with statement to avoid leaving the file open.

The key point is using 'a' for appending when you open the file.

import csv   
fields=['first','second','third']
with open(r'name', 'a') as f:
    writer = csv.writer(f)
    writer.writerow(fields)

If you are using Python 2.7 you may experience superfluous new lines in Windows. You can try to avoid them using 'ab' instead of 'a' this will, however, cause you TypeError: a bytes-like object is required, not 'str' in python and CSV in Python 3.6. Adding the newline='', as Natacha suggests, will cause you a backward incompatibility between Python 2 and 3.

北风几吹夏 2024-08-30 15:50:57

根据 @GM 的回答并注意 @John La Rooy 的警告,我能够附加一个新行,以 'a' 模式打开文件。

即使在Windows中,为了避免换行问题,也必须将其声明为newline=''

现在您可以以'a'模式打开文件(不带 b)。

import csv

with open(r'names.csv', 'a', newline='') as csvfile:
    fieldnames = ['This','aNew']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writerow({'This':'is', 'aNew':'Row'})

我没有尝试使用普通作家(没有字典),但我认为也可以。

Based in the answer of @G M and paying attention to the @John La Rooy's warning, I was able to append a new row opening the file in 'a'mode.

Even in windows, in order to avoid the newline problem, you must declare it as newline=''.

Now you can open the file in 'a'mode (without the b).

import csv

with open(r'names.csv', 'a', newline='') as csvfile:
    fieldnames = ['This','aNew']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writerow({'This':'is', 'aNew':'Row'})

I didn't try with the regular writer (without the Dict), but I think that it'll be ok too.

燕归巢 2024-08-30 15:50:57

如果您使用 pandas,您可以通过以下方式将数据帧附加到现有 CSV 文件:

df.to_csv('log.csv', mode='a', index=False, header=False)

使用 mode='a' 我们确保附加而不是覆盖,使用 header=False 我们确保仅附加 df 行的值,而不是标题+值。

If you use pandas, you can append your dataframes to an existing CSV file this way:

df.to_csv('log.csv', mode='a', index=False, header=False)

With mode='a' we ensure that we append, rather than overwrite, and with header=False we ensure that we append only the values of df rows, rather than header + values.

输什么也不输骨气 2024-08-30 15:50:57

您是否使用“a”模式而不是“w”模式打开文件?

请参阅 python 文档中的读取和写入文件

7.2。读写文件

open() 返回一个文件对象,最常与两个参数一起使用:open(filename, mode)。

<前><代码>>>> f = 打开('工作文件', 'w')
>>>>> print f <在 80a0960 打开文件“工作文件”,模式“w”>

第一个参数是包含文件名的字符串。第二个参数是
另一个字符串包含一些描述方式的字符
将使用该文件。当文件仅是时,模式可以是“r”
读取,“w”仅用于写入(具有相同名称的现有文件将
被删除),'a' 打开文件进行追加;任何写入的数据
该文件会自动添加到末尾。 'r+' 打开文件
阅读和写作。模式参数是可选的; 'r' 将是
如果省略则假定。

在 Windows 上,附加到模式后的“b”将以二进制模式打开文件,因此
还有“rb”、“wb”和“r+b”等模式。 Windows 上的 Python
区分文本文件和二进制文件;行尾
当数据被读取时,文本文件中的字符会自动稍微改变
被读取或写入。这种对文件数据的幕后修改
对于 ASCII 文本文件来说没问题,但它会损坏这样的二进制数据
在 JPEG 或 EXE 文件中。读取时要非常小心使用二进制模式
并编写此类文件。在 Unix 上,在后面附加一个“b”并没有什么坏处
模式,因此您可以独立于平台对所有二进制文件使用它
文件。

Are you opening the file with mode of 'a' instead of 'w'?

See Reading and Writing Files in the python docs

7.2. Reading and Writing Files

open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

>>> f = open('workfile', 'w')
>>> print f <open file 'workfile', mode 'w' at 80a0960>

The first argument is a string containing the filename. The second argument is
another string containing a few characters describing the way in which
the file will be used. mode can be 'r' when the file will only be
read, 'w' for only writing (an existing file with the same name will
be erased), and 'a' opens the file for appending; any data written to
the file is automatically added to the end. 'r+' opens the file for
both reading and writing. The mode argument is optional; 'r' will be
assumed if it’s omitted.

On Windows, 'b' appended to the mode opens the file in binary mode, so
there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows
makes a distinction between text and binary files; the end-of-line
characters in text files are automatically altered slightly when data
is read or written. This behind-the-scenes modification to file data
is fine for ASCII text files, but it’ll corrupt binary data like that
in JPEG or EXE files. Be very careful to use binary mode when reading
and writing such files. On Unix, it doesn’t hurt to append a 'b' to
the mode, so you can use it platform-independently for all binary
files.

一个人的旅程 2024-08-30 15:50:57

我使用以下方法在 .csv 文件中附加新行:

pose_x = 1 
pose_y = 2

with open('path-to-your-csv-file.csv', mode='a') as file_:
    file_.write("{},{}".format(pose_x, pose_y))
    file_.write("\n")  # Next line.

[注意]:

  • mode='a' 是附加模式。

I use the following approach to append a new line in a .csv file:

pose_x = 1 
pose_y = 2

with open('path-to-your-csv-file.csv', mode='a') as file_:
    file_.write("{},{}".format(pose_x, pose_y))
    file_.write("\n")  # Next line.

[NOTE]:

  • mode='a' is append mode.
高冷爸爸 2024-08-30 15:50:57

如果文件存在并包含数据,则可以自动为 csv.DictWriter 生成 fieldname 参数:

# read header automatically
with open(myFile, "r") as f:
    reader = csv.reader(f)
    for header in reader:
        break

# add row to CSV file
with open(myFile, "a", newline='') as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writerow(myDict)

If the file exists and contains data, then it is possible to generate the fieldname parameter for csv.DictWriter automatically:

# read header automatically
with open(myFile, "r") as f:
    reader = csv.reader(f)
    for header in reader:
        break

# add row to CSV file
with open(myFile, "a", newline='') as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writerow(myDict)
青春如此纠结 2024-08-30 15:50:57
# I like using the codecs opening in a with 
field_names = ['latitude', 'longitude', 'date', 'user', 'text']
with codecs.open(filename,"ab", encoding='utf-8') as logfile:
    logger = csv.DictWriter(logfile, fieldnames=field_names)
    logger.writeheader()

# some more code stuff 

    for video in aList:
        video_result = {}                                     
        video_result['date'] = video['snippet']['publishedAt']
        video_result['user'] = video['id']
        video_result['text'] = video['snippet']['description'].encode('utf8')
        logger.writerow(video_result) 
# I like using the codecs opening in a with 
field_names = ['latitude', 'longitude', 'date', 'user', 'text']
with codecs.open(filename,"ab", encoding='utf-8') as logfile:
    logger = csv.DictWriter(logfile, fieldnames=field_names)
    logger.writeheader()

# some more code stuff 

    for video in aList:
        video_result = {}                                     
        video_result['date'] = video['snippet']['publishedAt']
        video_result['user'] = video['id']
        video_result['text'] = video['snippet']['description'].encode('utf8')
        logger.writerow(video_result) 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文