python - 在Python中使用seek()

标签 python

我正在努力读取特定的动态心电图数据(.ecg 文件)并将用户指定的特定数据复制到新文件中。基本上,我只想将必要的数据读入内存。有没有办法使用 .seek() 只从(开始,结束)读取数据字节?

start = args.packet_start
end = args.packet_end

try:

    print("Beginning copying of holter data...")

    # Output the specific holter data
    output_file = open("copied_holter.ecg", 'w')

    # Read part of holter file into memory
    holter = open(args.filename, 'rb')
    data = holter.seek()

# Parse through holter data and copy to file
    for index in range(start, end+1):
    data_list = data[index]
    output_file.write(data_list)

    # Close the file streams
    holter.close()
    output_file.close()  

except Exception as e:
    print(e)
    print("Exiting program, due to exception.")
    exit(1)

print "Finished data copying operations!"

最佳答案

seek 会将指针移动到指定位置,而不返回数据。 read 将返回指定的字节数。此外,在处理文件或类似文件的对象时,您应该使用 with 语句。

with open(args.filename, 'rb') as holter, open("copied_holter.ecg", 'w') as output_file:
    holter.seek(start)
    data = holter.read(end-start)
    output_file.write(data)

关于python - 在Python中使用seek(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35344322/

相关文章:

python - 在Python中迭代列表时更改要迭代的元素

python - 属性错误: 'NoneType' object has no attribute 'split' while execute pelican-quickstart

python - 让 x 轴网格显示在 matplotlib 中

python - matrix**2 在 python/numpy 中是什么意思?

python - Mechanize :类型错误: 'NoneType' 对象不支持项目分配

python - 对 Tastypie 的 POST 请求返回一个非 SSL Location Header

python - 线程中未标记的异常

python - 如何使用 Python 和 RegEx 匹配文本文件中的整行并将其分解为变量?

python - 如何设置pip环境路径?

python - 查找值位于 PySpark Dataframe 中特定列之间的所有列的列表