gpt4 book ai didi

python-3.x - 后续搜索特定文件扩展名的目录并执行求和以将它们的内容加在一起

转载 作者:行者123 更新时间:2023-12-01 13:18:57 24 4
gpt4 key购买 nike

这是我的 previous post 的跟进.本质上,这个想法是将/home/pi/math 中所有以 .math 结尾的文件的内容相加。目录。目前我有 3 个文件:test.math、hello.math、hi.math - 它们都至少有 1.00。问题是 1. 它似乎没有正确读取文件的内容,也没有将它们相加。

这个想法是它会添加这 3 个文件(最终我想将它们添加到一个变量中)并显示总数。请注意,我确实想包括花车。

import os

srcdir = "/home/pi/math/"
files = os.listdir(srcdir)


def sum_file_contents():
value = float()
for file in srcdir:
if file.endswith(('math')):
value += float(open(file, "r").read().strip())
return value

for file in files:
if file.endswith(('math')):
print(file)
print(sum_file_contents())

输出

test.math
0.0
hello.math
0.0
hi.math
0.0

最佳答案

您的主 for 循环遍历 files,它来自 os.listdir(srcdir),然后您的 sum_file_contents( ) 尝试再次做同样的事情,只是它以字符串形式遍历 srcdir,这自然不会为您提供目录列表。主 for 循环是多余的,您应该在遍历它时通过调用 os.listdir() 简单地修复 sum_file_contents():

import os

srcdir = "/home/pi/math/"

def sum_file_contents():
value = float()
for file in os.listdir(srcdir):
if file.endswith(('math')):
value += float(open(os.path.join(srcdir, file), "r").read().strip())
return value
print(sum_file_contents())

关于python-3.x - 后续搜索特定文件扩展名的目录并执行求和以将它们的内容加在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51664052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com