读取和写入临时文件

reading and writing a tempfile

希望有人能帮助我。这似乎是一个非常简单的问题,我就是找不到答案。我正在尝试创建一个临时文件,然后使用同一个临时文件,我想使用 dd 命令写入它。然后打开同一个文件并计算读取文件所需的时间。

我不确定为什么,但这是我遇到的错误。类型错误:强制转换为 Unicode:需要字符串或缓冲区,已找到实例。我认为这是因为我同时打开了相同的文件,但不确定。有什么想法吗?

代码如下:

import time
import tempfile
import subprocess
import argparse

def readfile(size, block_size, path):
    with tempfile.NamedTemporaryFile(prefix='iospeeds-', dir=path, delete=True) as tf: 

        cmd = ['dd', 'if=/dev/zero', 'of={}'.format(tf), 'bs={}'.format(block_size), 'count={}'.format(size/block_size)]
        subprocess.call(cmd, stderr=subprocess.STDOUT)

        start_time = time.time()
        with open(tf, 'rb') as read_file:
            end_time = time.time()
        total_time = start_time - end_time



    print total_time
    return total_time

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--size', type=int, default=1048576)
    parser.add_argument('--block-size', type=int, default=4096)
    parser.add_argument('--path', default='./')
    return parser.parse_args()

def main():
    args=parse_args()
    size = args.size
    block_size = args.block_size 
    path = args.path
    readfile(size, block_size, path)

if __name__ == "__main__":
    main()

这是回溯:

Traceback (most recent call last):
  File "./rd.py", line 38, in <module>
    main()
  File "./rd.py", line 35, in main
    readfile(size, block_size, path)
  File "./rd.py", line 14, in readfile
    with open(tf, 'rb') as read_file: 

谢谢!

您正在尝试打开名称点中文件类型的文件,基本上您是在尝试执行 open(file, 'rb') 而不是 open(filename, 'rb')。尝试:

with open(tf.name, 'rb') as read_file: