同时读取和写入CSV文件

时间:2018-10-12 06:25:35

标签: python python-3.x

我想从csv文件中读取一些输入,然后修改输入并将其替换为新值。为此,我首先读取了该值,但是由于要修改文件中存在的所有值,因此目前处于卡住状态。 那么可以在一个for循环中以r模式打开文件,然后在另一个循环中立即以w模式打开文件以输入修改后的数据吗?

如果有更简单的方法,请帮帮我

谢谢。

3 个答案:

答案 0 :(得分:1)

您可以执行open("data.csv", "rw"),这使您可以同时进行读写。

答案 1 :(得分:1)

是的,您可以在同一程序中以不同的模式打开同一文件。只是要确保不要同时进行。例如,这是完全有效的:

with open("data.csv") as f:
  # read data into a data structure (list, dictionary, etc.)
  # process lines here if you can do it line by line

# process data here as needed (replacing your values etc.)

# now open the same filename again for writing
# the main thing is that the file has been previously closed
# (after the previous `with` block finishes, python will auto close the file)
with open("data.csv", "w") as f:
  # write to f here

正如其他人在评论中指出的那样,同时在同一文件句柄上进行读写通常是一个坏主意,并且不会按您期望的那样工作(除非对于某些非常特殊的用例)。

答案 2 :(得分:0)

就像其他人提到的那样,在没有任何备份方法的情况下将相同的文件修改为输入和输出,这是一个可怕的想法,尤其是在像大多数.csv文件这样的压缩文件中,通常比单个文件更复杂基于.Txt的文件,但是如果您坚持要执行以下操作:

import csv

file path = 'some.csv'

with open('some.csv', 'rw', newline='') as csvfile:
    read_file = csv.reader(csvfile)
    write_file = csv.writer(csvfile)

请注意,上面的代码将触发错误,并显示一条消息ValueError: must have exactly one of create/read/write/append mode

为了安全起见,我更喜欢将其分成两个不同的文件

import csv

in_path = 'some.csv'
out_path = 'Out.csv'

with open(in_path, 'r', newline='') as inputFile, open(out_path, 'w', newline='') as writerFile:
    read_file = csv.reader(inputFile)
    write_file = csv.writer(writerFile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

    for row in read_file:
    # your modifying input data code here
    ........