将文件夹和文件夹的文件夹写入使用Python 3.7的文本文件

发布于 2025-01-26 05:26:52 字数 694 浏览 3 评论 0原文

我正在使用Python 3.7。 我想检查文本文件的文件路径的目录的文件大小。

这是我的代码:

import os
import glob


# folder path
folderpath = 'C:/Test'

# Get a list of files in my folder
list_of_files = filter( os.path.isfile,
                        glob.glob(folderpath + '*') )

# get list of files with the size in my folder
files_with_size = [ (file_path, os.stat(file_path).st_size)
                    for file_path in list_of_files ]

# Iterate over the files and write them to a file
for file_path, file_size in files_with_size:
    with open('c:/Test/filesize.txt', 'w') as f:
        print(file_size, ' -->', file_path)

我可以在Python控制台中打印结果,但是我无法将结果写入文本文件。 有人可以帮我吗?

问候, 扬

I am using Python 3.7.
I want to check the file sizes of a directory with the file path to a text file.

This is my code:

import os
import glob


# folder path
folderpath = 'C:/Test'

# Get a list of files in my folder
list_of_files = filter( os.path.isfile,
                        glob.glob(folderpath + '*') )

# get list of files with the size in my folder
files_with_size = [ (file_path, os.stat(file_path).st_size)
                    for file_path in list_of_files ]

# Iterate over the files and write them to a file
for file_path, file_size in files_with_size:
    with open('c:/Test/filesize.txt', 'w') as f:
        print(file_size, ' -->', file_path)

I can print the result in the Python console, but I cannot manage to write my result to a text file.
Can anybody help me?

Regards,
Jan

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

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

发布评论

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

评论(1

蓝戈者 2025-02-02 05:26:52

我会将您的代码遵循以下方式

for file_path, file_size in files_with_size:
    with open('c:/Test/filesize.txt', 'a') as f:
        print(file_size, ' -->', file_path, file=f)

变更:使用a(附加)模式,然后使用f作为new hehref = of note grigent file 的值“ https://docs.python.org/3/library/functions.html#print” rel =“ nofollow noreferrer”> print> print 函数。

I would ameloriate your code following way

for file_path, file_size in files_with_size:
    with open('c:/Test/filesize.txt', 'a') as f:
        print(file_size, ' -->', file_path, file=f)

changes: use a (append) mode and use f as value for named argument file of print function.

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