次の場合(最初の行には先頭のスペースがないことに注意してください):
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
....
481 total rows
次の例では、先頭のスペースが正しく削除されますが、各文字列行の後に空白行が挿入され、ANDは、実行されるたびにランダムな行数でリスト全体を切り捨てます。
csvfile= open('list.csv','r')
csvfile1= open('complete_list.csv','w')
stripped = (row.strip() for row in csvfile)
reader = csv.reader(stripped,delimiter=' ')
writer= csv.writer(csvfile1)
for row in reader:
writer.writerow([e.strip() for e in row])
そして:
with open('list.csv') as infile:
reader = csv.DictReader(infile)
fieldnames = reader.fieldnames
for row in reader:
row.update({fieldname: value.strip() for (fieldname, value) in row.items()})
最初の行はフィールド名であると想定されているため、実際には単に...行であるにもかかわらず、何もしません。
ここでいくつかの問題:
newline=""
、Windowsに空白が挿入されますstrip
がlstrip
、行上にあります。使用しないと、行末の改行が削除されます。csvリーダーを混乱させる可能性がありますwith
コンテキストブロックを使用して、ブロックを終了するときにファイルが確実に閉じられるようにします(最後にランダムに欠落している行を処理する必要があります)私の提案:
with open('list.csv','r') as csvfile, open('complete_list.csv','w',newline="") as csvfile1: # newline="" to avoid blanks
stripped = (row.lstrip() for row in csvfile) # lstrip not strip
reader = csv.reader(stripped,delimiter=' ')
writer= csv.writer(csvfile1)
writer.writerows(reader) # don't overstrip: just write rows as-is
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加