Pythonで書かれたCSVファイルには各行の間に空白行があります 質問する

Pythonで書かれたCSVファイルには各行の間に空白行があります 質問する
import csv

with open('thefile.csv', 'rb') as f:
  data = list(csv.reader(f))
  import collections
  counter = collections.defaultdict(int)

  for row in data:
        counter[row[10]] += 1


with open('/pythonwork/thefile_subset11.csv', 'w') as outfile:
    writer = csv.writer(outfile)
    for row in data:
        if counter[row[10]] >= 504:
           writer.writerow(row)

このコードは を読み取りthefile.csv、変更を加え、結果を に書き込みますthefile_subset1

しかし、結果の csv を Microsoft Excel で開くと、各レコードの後に​​余分な空白行があります。

余分な空白行を入れないようにする方法はありますか?

ベストアンサー1

モジュールcsv.writerは行末を直接制御し、\r\nファイルに直接書き込みます。Python 3では、パラメータ'w', newline=''(空の文字列) を使用してファイルを未翻訳テキスト モードで開く必要があります。そうしないと、Windows に書き込まれ、デフォルトのテキスト モードではそれぞれが に\r\r\n変換されます。\n\r\n

#!python3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)

モジュールを使用する場合Path:

from pathlib import Path
import csv

with Path('/pythonwork/thefile_subset11.csv').open('w', newline='') as outfile:
    writer = csv.writer(outfile)

モジュールを使用してメモリ内の結果を構築する場合StringIO、結果文字列には変換された行終端文字が含まれます。

from io import StringIO
import csv

s = StringIO()
writer = csv.writer(s)
writer.writerow([1,2,3])
print(repr(s.getvalue()))  # '1,2,3\r\n'   (Windows result)

後でその文字列をファイルに書き込む場合は、次の点に注意してくださいnewline=''

# built-in open()
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as f:
    f.write(s.getvalue())

# Path's open()
with Path('/pythonwork/thefile_subset11.csv').open('w', newline='') as f:
    f.write(s.getvalue())

# Path's write_text() added the newline parameter to Python 3.10.
Path('/pythonwork/thefile_subset11.csv').write_text(s.getvalue(), newline='')

Python 2では、 Windowsの改行変換を防ぐために、 ではなくバイナリモードoutfileで開きます。Python 2はUnicodeにも問題があり、非ASCIIテキストを書き込むには他の回避策が必要です。Python 2でUnicode文字列をCSVに書き込む必要がある場合は、以下のPython 2リンクとページの最後にある例を参照してください。または、サードパーティの'wb''w'UnicodeReaderUnicodeWriterユニコードモジュール:

#!python2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
    writer = csv.writer(outfile)

ドキュメントリンク

おすすめ記事