簡體   English   中英

根據查詢Python寫入CSV中的特定行

[英]Write to specific row in CSV according to query Python

我正在嘗試在csv文件中查找值,如果找到它,請在其行末尾寫回一個值。 例如,如果csv如下所示:

 #   A  B 
111  1
112  0
113  0
114  1

我查找111並想在其行的第一個空單元格中寫入0,該怎么辦?

無法在文件中間插入數據。 寫入文件中間將覆蓋該位置的數據。 代替:

  • 以讀取模式打開文件
  • 讀取文件中的所有數據
  • 關閉檔案
  • 在寫入模式下重新打開文件
  • 寫前幾行
  • 寫您的額外數據
  • 寫入其余的原始數據

一個例子:

with open('test.csv') as f:
l = f.readlines()

l[4] += '0'
with open('test2.csv', 'w') as f:
    f.writelines(l)
with open('text.csv', 'r') as f:
    rows = [x.split() for x in f]
with open('text_1.csv', 'w') as f:
    for row in rows:
        f.write(row[0] + " " + row[1])
        if row[0] == '111': # or you can check for multiple values here.
            f.write("0")
        f.write("\n")

這樣一來,您就可以在單個上下文管理器中打開, 讀取和寫入文件

search_term = '112' # This is what you are looking 
                    # for at the start of the lines.
##-------------------------------------------------------##
# Define separator
sep = '\t' # Use '\t' (TAB) or " " (SPACE)
val = 0 # This is the value you want to insert 
        # at the end of the target line.
##-------------------------------------------------------##
write_to_file = False # Set this to True when 
                      # you want to write to the file.

##-------------------------------------------------------##
with open("dummy.csv","r+") as f:
    content = f.readlines()
    for i,line in enumerate(content):
        if line.startswith(search_term):
            line = line.strip() + '{}{}\n'.format(sep,val)
            content[i] = line
    if write_to_file:
        f.writelines(content)

print(''.join(content))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM