Python glob 没有给出结果

标签 python file-io python-3.5 glob

我有一个包含大量 .csv 文件的目录,我正在尝试编写一个在目录中的所有文件上运行的脚本,同时执行以下操作:

Remove the first and last lines from all the csv files

我正在运行以下代码:

import glob

list_of_files = glob.glob('path/to/directory/*.csv')
for file_name in list_of_files:
    fi = open(file_name, 'r')
    fo = open(file_name.replace('csv', 'out'), 'w')  #make new output file for each file
    num_of_lines = file_name.read().count('\n')
    file_name.seek(0)
    i = 0
    for line in fi:
        if i != 1 and i != num_of_lines-1:
            fo.write(line)

    fi.close()
    fo.close()

我使用python3 script.py运行脚本。虽然我没有收到任何错误,但我也没有收到任何输出文件。

最佳答案

您的代码中存在多个问题。首先,计算文件名而不是文件对象的行数。第二个问题是您初始化 i=0 并与它进行比较,但它永远不会改变。

就我个人而言,我只是将文件转换为“行”列表,切断第一个和最后一个并将它们全部写入新文件:

import glob

list_of_files = glob.glob('path/to/directory/*.csv')
for file_name in list_of_files:
    with open(file_name, 'r') as fi:
        with open(file_name.replace('csv', 'out'), 'w') as fo:
            for line in list(fi)[1:-1]:  # for all lines except the first and last
                fo.write(line)

使用 with open 可以省略 close 调用(因为它们是隐式完成的),即使发生异常也是如此。

<小时/>

如果仍然没有输出,您可以使用 print 语句来显示正在处理的文件:

print(file_name)  # just inside the for-loop before any `open` calls.
<小时/>

由于您使用的是 python-3.5,您还可以使用 pathlib:

import pathlib

path = pathlib.Path('path/to/directory/')

# make sure it's a valid directory
assert path.is_dir(), "{} is not a valid directory".format(p.absolute())

for file_name in path.glob('*.csv'):
    with file_name.open('r') as fi:
        with pathlib.Path(str(file_name).replace('.csv', '.out')).open('w') as fo:
            for line in list(fi)[1:-1]:  # for all lines except the first and last
                fo.write(line)
<小时/>

正如 Jon Clements 指出的那样,有一种比 [1:-1] 更好的方法来使用生成器函数排除第一行和最后一行。这样您肯定会减少内存使用量,并且还可能提高整体性能。例如,您可以使用:

import pathlib

def ignore_first_and_last(it):
    it = iter(it)
    firstline = next(it)
    lastline = next(it)
    for nxtline in it:
        yield lastline
        lastline = nxtline

path = pathlib.Path('path/to/directory/')

# make sure it's a valid directory
assert path.is_dir(), "{} is not a valid directory".format(p.absolute())

for file_name in path.glob('*.csv'):
    with file_name.open('r') as fi:
        with pathlib.Path(str(file_name).replace('.csv', '.out')).open('w') as fo:
            for line in ignore_first_and_last(fi):  # for all lines except the first and last
                fo.write(line)

关于Python glob 没有给出结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45693176/

相关文章:

python - 我的python代码出现问题

python - 如何将多维数据框压缩为单列?

java - FileOutputStream 文件未找到错误

python - multiprocessing.Pool 似乎可以在 Windows 中使用,但不能在 ubuntu 中使用?

java - 公式解决方案

c# - .NET File.Create,之后无法删除文件

python - 在 Python 中打印 {1}

python - 打字模块 - 字符串字面量类型

python - 如何使用 XPath lxml Python 选择直接子项?

javascript - Python - 在两个浏览器之间传输 session