【问题标题】:Delete blank rows in a csv file in Python在 Python 中删除 csv 文件中的空白行
【发布时间】:2018-11-28 12:00:56
【问题描述】:

我的文件夹中有一些 csv 文件,我正在尝试删除所有空白行并将新闻文件移动到新文件夹中。

这是我的代码:

import csv
import glob
import os
import shutil

path = 'in_folder/*.csv'
files=glob.glob(path)

#Read every file in the directory

x = 0 #counter

for filename in files:

    with open(filename, 'r') as fin:
        data = fin.read().splitlines(True)

        with open(filename, 'w') as fout:
            for line in fin.readlines():
                if ''.join(line.split(',')).strip() == '':
                    continue
                fout.write(line)
            x += 1            


dir_src = "in_folder"
dir_dst = "out_folder"


for file in os.listdir(dir_src):
    if x>0:
        src_file = os.path.join(dir_src, file)
        dst_file = os.path.join(dir_dst, file)
        shutil.move(src_file, dst_file)

代码现在正在做的是从文件中删除所有内容并将它们移动到新文件夹中。我希望我的文件相同,但删除了空白行。

【问题讨论】:

  • 那你要修改原来的吗?删除原件?
  • 或者在 Perl 中(示例是单个文件)!! - perl -ni.old -e '打印除非 /^\s*$/' 文件 (stackoverflow.com/a/8270397/1755628)
  • @PeterWood 删除空行,并将新文件放入新文件夹。
  • 你说的不准确。你想要原始文件消失吗?如果没有,您要修改原始文件吗?
  • 我要修改原文件。

标签: python file csv


【解决方案1】:

你可以将每一行输出到新文件中,之后不需要做任何移动:

dir_src = "in_folder/*.csv"
dir_dst = "out_folder"

files = glob.glob(dir_src)

# Read every file in the directory

x = 0 # counter

for filename in files:
    outfilename = os.path.join(dir_dst, os.path.basename(filename))
    with open(filename, 'r') as fin:
        with open(outfilename, 'w') as fout:
            for line in fin:
                if ''.join(line.split(',')).strip() == '':
                    continue
                fout.write(line)
            x += 1            

【讨论】:

    【解决方案2】:

    试试这个。

    for filename in files:
        with open(filename, 'r') as fin:
            data = fin.read().splitlines(True)
            with open(filename, 'w') as fout:
                for line in data:
                    if ''.join(line.split(',')).strip() == '':
                        continue
                    fout.write(line)
                x += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      • 1970-01-01
      • 2018-03-24
      • 2011-05-30
      • 2021-02-18
      • 1970-01-01
      • 2016-12-26
      相关资源
      最近更新 更多