从目录到.csv列的文件名(每行的文件名;无间隙(行)

2024-04-24 12:24:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我用下面的代码很快就做到了这一点:但是,问题是在每个文件名的行之间都有一个空白行。我试过使用r, w, and w+——有没有什么想法可以在每一行之间不留空白行的情况下实现这一点

import config
import math
import os, csv

with open(config.CSV, 'w+') as f:
    writer = csv.writer(f)
    for path, dirs, files in os.walk(config.files):
        for filename in files:
            writer.writerow([filename])

CVS输出如下:(写入文件名;但不希望必须手动处理这些额外的空格/它们之间的空白行)

1 | filename1.pdf
2 |
3 | filename2.pdf
4 |
5 | filename3.pdf

Tags: andcsv代码inimportconfigforpdf
2条回答

我相信这是因为当你读你的文件时,你的结尾有一个不可见的'\n'。把它取下来就好了

您应该打开文件by passing ^{} option

csv.writer(csvfile, dialect='excel', **fmtparams) Return a writer object responsible for converting the user’s data into delimited strings on the given file-like object. csvfile can be any object with a write() method. If csvfile is a file object, it should be opened with newline=''

footnote clarifies

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

相关问题 更多 >