相关疑难解决方法(0)

将字节转换为字符串?

我正在使用此代码从外部程序获取标准输出:

>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)

communic()方法返回一个字节数组:

>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n'
Run Code Online (Sandbox Code Playgroud)

但是,我想将输出作为普通的Python字符串.所以我可以这样打印:

>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2
Run Code Online (Sandbox Code Playgroud)

我认为这是binascii.b2a_qp()方法的用途,但是当我尝试它时,我又得到了相同的字节数组:

>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n'
Run Code Online (Sandbox Code Playgroud)

有人知道如何将字节值转换回字符串吗?我的意思是,使用"电池"而不是手动操作.而且我希望它能用于Python 3.

python string python-3.x

1968
推荐指数
18
解决办法
203万
查看次数

读取二进制文件并循环遍历每个字节

在Python中,如何读取二进制文件并循环遍历该文件的每个字节?

python binary file-io

345
推荐指数
9
解决办法
75万
查看次数

文件句柄在超出范围后是否会在Python中自动关闭?

如果我执行以下操作,文件句柄会在Python中超出范围时自动关闭:

def read_contents(file_path):
  return file(file_path).read()
Run Code Online (Sandbox Code Playgroud)

如果没有,我该怎么写这个函数来自动关闭范围?

python scope file

22
推荐指数
2
解决办法
8373
查看次数

在python中读取二进制文件

我必须在python中读取二进制文件.这首先是由Fortran 90程序以这种方式编写的:

open(unit=10,file=filename,form='unformatted')
write(10)table%n1,table%n2
write(10)table%nH
write(10)table%T2
write(10)table%cool
write(10)table%heat
write(10)table%cool_com
write(10)table%heat_com
write(10)table%metal
write(10)table%cool_prime
write(10)table%heat_prime
write(10)table%cool_com_prime
write(10)table%heat_com_prime
write(10)table%metal_prime
write(10)table%mu
if (if_species_abundances) write(10)table%n_spec
close(10)
Run Code Online (Sandbox Code Playgroud)

我可以使用以下IDL代码轻松读取此二进制文件:

n1=161L
n2=101L
openr,1,file,/f77_unformatted
readu,1,n1,n2
print,n1,n2
spec=dblarr(n1,n2,6)
metal=dblarr(n1,n2)
cool=dblarr(n1,n2)
heat=dblarr(n1,n2)
metal_prime=dblarr(n1,n2)
cool_prime=dblarr(n1,n2)
heat_prime=dblarr(n1,n2)
mu  =dblarr(n1,n2)
n   =dblarr(n1)
T   =dblarr(n2)
Teq =dblarr(n1)
readu,1,n
readu,1,T
readu,1,Teq
readu,1,cool
readu,1,heat
readu,1,metal
readu,1,cool_prime
readu,1,heat_prime
readu,1,metal_prime
readu,1,mu
readu,1,spec
print,spec
close,1
Run Code Online (Sandbox Code Playgroud)

我想要做的是用Python读取这个二进制文件.但是有一些问题.首先,这是我尝试阅读该文件:

import numpy
from numpy import *
import struct

file='name_of_my_file'
with open(file,mode='rb') as lines:
    c=lines.read()
Run Code Online (Sandbox Code Playgroud)

我尝试阅读前两个变量:

dummy, n1, n2, dummy = struct.unpack('iiii',c[:16])
Run Code Online (Sandbox Code Playgroud)

但是你可以看到我必须添加到虚拟变量,因为不知何故,fortran程序在这些位置添加整数8.

现在问题是在尝试读取其他字节时.我没有得到相同的IDL程序结果.

这是我尝试读取数组n …

python idl-programming-language

4
推荐指数
1
解决办法
7231
查看次数