簡體   English   中英

用CSV替換單詞而不用python知道它的位置

[英]Replacing word in CSV without knowing it's position with python

我試圖在幾個巨大的CSV文件中查找單詞NIL的出現,並將其替換為空字符串。 我已經查找了解決方案,但是我嘗試的解決方案不起作用,因為該行是一個列表 ,而我發現的其他解決方案似乎位於特定位置,但是我不知道NIL會出現在哪里,因為文件位於總是在變化。

我的代碼:

import Tkinter, tkFileDialog, os, csv

root = Tkinter.Tk()
root.withdraw()
dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
for subdir, dirs, files in os.walk(dirname):
    for file in files:
        with open (os.path.join(subdir, file), 'rb') as csvfile:
            #Check if the file has headers#
            if 'Result  :  Query Result' in csvfile.readline():
                with open(os.path.join(subdir, os.path.splitext(file)[0] + '_no_headers_no_nil.csv'), 'wb') as out:
                    reader = csv.reader(csvfile.readlines()[6:], delimiter=',')
                    writer = csv.writer(out)
                    for row in reader:
                        #replace NIL occurrences with empty strings
                        row = row.replace('NIL', '')
                        separated = row.split(',')
                        writer.writerow(row)

            else:
                #The file doesn't have headers
                #find and replace NIL occurrences goes here
                print 'file skipped ' + file + ': No headers found'

這是CSV類型的示例

CSV范例

如果Nil不是在獲取索引的每一行中都沒有,而是僅分配給一個空字符串,則使用try / except:

try:

    row[row.index("NIL")] = ""
except IndexError:
    pass

索引將找到Nil在您的列表中的位置,一旦您知道該分配將替換它:

In [9]: lst = ["NIL", "foo"]

In [10]: lst[lst.index("NIL")] = ""

In [11]: lst
Out[11]: ['', 'foo']

由於每行可以有多個NIL字符串,因此需要遍歷每個元素:

row[:] = [ele if ele != "NIL" else "" for ele in row] 

同樣,您不需要調用readlines,可以使用itertools.islice從第n行開始:

from itertools import islice

reader = csv.reader(islice(csvfile, 6, None), delimiter=',')

暫無
暫無

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

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