python - 文件大小总和的脚本

标签 python

我正在尝试计算各种文件的大小总和。这是我的脚本:

import os
date = raw_input('Enter date in format YYYYMMDD ')
file1 = 'p_poupe_' + date + '.tar.gz.done'
file2 = 'p_poupw_' + date + '.tar.gz.done'
file3 = 'p_pojk_' + date + '.tar.gz.done'

a1 = os.system('zcat ' + file1 + '|wc --bytes')
a2 = os.system('zcat ' + file2 + '|wc --bytes')
a3 = os.system('zcat ' + file3 + '|wc --bytes')

print a1,a2,a3
sum = a1 + a2 + a3

print sum

但是这些值没有存储在变量中。谁能告诉我我做错了什么。如何修改脚本以便将值存储在变量中而不是作为输出。

最佳答案

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit status of the command run; on systems using a non-native shell, consult your shell documentation.

https://docs.python.org/2/library/os.html#os.system

问题是您使用退出代码而不是标准输出数据作为您的“值”。 例如,您可能希望使用 subprocess.Popen 。或者只是通过打开文件手动编写解决方案。

尝试使用https://docs.python.org/3/library/gzip.html

import gzip
def get_fcont_len(fname):
    with gzip.open(fname) as f:
        return len(f.read())
total = 0
date = raw_input('Enter date in format YYYYMMDD ')
total += get_fcont_len('p_poupe_' + date + '.tar.gz.done')
total += get_fcont_len('p_poupw_' + date + '.tar.gz.done')
total += get_fcont_len('p_pojk_' + date + '.tar.gz.done')
print(total)

关于python - 文件大小总和的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29032362/

相关文章:

python - 如何从python中的nd数组中提取特定行

python - pytransitions 中的 get_triggers() 未返回预期输出

python - 将多个 if 语句放入 python pandas 的一个 if 语句中

python - scrapy的Request函数没有被调用

Python write() 方法和 close() 函数不适用于最新版本的 Visual Studio Code。代码适用于 Python 3.8.5 Shell

python - 使用引用日期解析自然/人类日期

python - 高效更新 Pandas sql

python - 如何找到给定文件的路径?

python - IP摄像机Python错误

python - 如何在管道中使用 `subprocess` 命令