Python,csv writer 之后的空文件..再次

发布于 2024-12-09 05:49:32 字数 1277 浏览 0 评论 0原文

我的 python 程序循环遍历一堆 csv 文件,读取它们,并将文件中的特定列写入另一个 csv 文件。当程序运行时,我可以看到文件正在以正确的方式写入,但是一旦程序完成,我刚刚写入的所有文件都会变成空。

所有其他类似线程的解决方案似乎是正确关闭您写入的文件,但我似乎无法弄清楚我做错了什么。有人吗?

import os
import csv

def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d)

readpath = os.path.join("d:\\", "project")
savepath=os.path.join("d:\\", "save")
ensure_dir(savepath)
contents_1=os.listdir(readpath)
for i in contents_1[1:len(contents_1)]:
    readpath_2=os.path.join(readpath, i)
    if os.path.isdir(readpath_2)== True :
        contents_2=os.listdir(readpath_2)
        for i in contents_2:
            readpath_3=os.path.join(readpath_2, i)
            if os.path.isfile(readpath_3)== True :
                savefile=savepath + "\\" + i
                savefile = open(savefile, 'wb')
                writer = csv.writer(savefile, delimiter=';')
                readfile=open(readpath_3, 'rb')
                reader = csv.reader(readfile, delimiter=';')
                try:
                    for row in reader:
                        writer.writerow([row[0], row[3]])
                except:
                    print(i)
                finally:
                    savefile.close()
                    readfile.close()

My python program loops through a bunch of csv-files, read them, and write specific columns in the file to another csv file. While the program runs, i can see the files being written in the correct manner, but once the program is finished, all the files i've just written become empty.

The solution to all the other similar threads seems to be closing the file you write to properly, but i cant seem to figure out what im doing wrong. Anyone?

import os
import csv

def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d)

readpath = os.path.join("d:\\", "project")
savepath=os.path.join("d:\\", "save")
ensure_dir(savepath)
contents_1=os.listdir(readpath)
for i in contents_1[1:len(contents_1)]:
    readpath_2=os.path.join(readpath, i)
    if os.path.isdir(readpath_2)== True :
        contents_2=os.listdir(readpath_2)
        for i in contents_2:
            readpath_3=os.path.join(readpath_2, i)
            if os.path.isfile(readpath_3)== True :
                savefile=savepath + "\\" + i
                savefile = open(savefile, 'wb')
                writer = csv.writer(savefile, delimiter=';')
                readfile=open(readpath_3, 'rb')
                reader = csv.reader(readfile, delimiter=';')
                try:
                    for row in reader:
                        writer.writerow([row[0], row[3]])
                except:
                    print(i)
                finally:
                    savefile.close()
                    readfile.close()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

计㈡愣 2024-12-16 05:49:32

savefile=savepath + "\\" + i 是错误。如果 "d:\\project\a\x.csv""d:\\project\b\x.csv" 都存在,那么您将写入savepath + "\\" + i 多次。如果第二个路径是空的“x.csv”,那么它将用空文件覆盖结果。

试试这个:

import os
import csv

def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d)

readpath = os.path.join("d:\\", "project")
savepath = os.path.join("d:\\", "save")

ensure_dir(savepath)

for dname in os.listdir(readpath)[1:]:
    readpath_2 = os.path.join(dname, fname)
    if not os.path.isdir(readpath_2):
        continue
    for fname in os.listdir(readpath_2)
        fullfname = os.path.join(readpath_2, fname)
        if not os.path.isfile(fullfname):
            continue
        savefile = open(savepath + "\\" + dname + "_" + fname, wb)
        writer = csv.writer(savefile, delimiter=';')
        readfile=open(fullfname, 'rb')
        reader = csv.reader(readfile, delimiter=';')
        try:
            for row in reader:
                writer.writerow([row[0], row[3]])
        except:
            print(i)
        finally:
            savefile.close()
            readfile.close()

使用 os.walk

savefile=savepath + "\\" + i is the error. If both "d:\\project\a\x.csv" and "d:\\project\b\x.csv" exist, then you will write to savepath + "\\" + i more than once. If the second path as an empty "x.csv", then it would overwrite the result with an empty file.

Try this instead:

import os
import csv

def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d)

readpath = os.path.join("d:\\", "project")
savepath = os.path.join("d:\\", "save")

ensure_dir(savepath)

for dname in os.listdir(readpath)[1:]:
    readpath_2 = os.path.join(dname, fname)
    if not os.path.isdir(readpath_2):
        continue
    for fname in os.listdir(readpath_2)
        fullfname = os.path.join(readpath_2, fname)
        if not os.path.isfile(fullfname):
            continue
        savefile = open(savepath + "\\" + dname + "_" + fname, wb)
        writer = csv.writer(savefile, delimiter=';')
        readfile=open(fullfname, 'rb')
        reader = csv.reader(readfile, delimiter=';')
        try:
            for row in reader:
                writer.writerow([row[0], row[3]])
        except:
            print(i)
        finally:
            savefile.close()
            readfile.close()

This code could be greatly improved with os.walk

三五鸿雁 2024-12-16 05:49:32

引用自python文档:

如果 csvfile 是文件对象,则必须在有区别的平台上使用“b”标志打开它。

将“w”和“r”标志更改为“wb”和“rb”。

Quoting from the python documentation:

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

Change the 'w' and 'r' flags to 'wb' and 'rb'.

忘你却要生生世世 2024-12-16 05:49:32

(1) 外循环和内循环都使用 i 作为循环变量。这不可能 (a) 被人类理解 (b) 正常工作。

(2) 除了:print(i) ...什么???我建议您删除 try/ except 并修复遇到的任何错误。

(1) Your outer loop AND your inner loop both use i as the loop variable. This has no hope of (a) being understood by a human (b) working properly.

(2) except: print(i) ... What??? I'd suggest you remove the try/except and fix any bugs that you come across.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文