我用python编写了一个二进制解码器,但是我无法将文本文件传递给它。
"""
Date :28/3/17
File Name:binary_to_string.py
"""
import sys
def binary_to_str(binary_string):
"""
This function take a binary string as argument and convert to string
:param binary_string: string in 0 or 1 from
:return:
"""
bits = 8 # initialize bit to 8 means by default we are assuming 8 bit binary
# checking for backslash if we found first 8 bit give backslash then we reassign bit to 7
if ord(chr(int(binary_string[:8], 2))) == 145:
bits = 7
result_string = ''
# iterate all group of 7 or 8 character in binary string based on bits
# and append to result string
for i in range(0, len(binary_string), bits):
result_string += chr(int(binary_string[i:i + bits], 2))
return result_string
def read_file(file_name):
"""
This function takes file name as input and read file line by line and
append to binary_str and return it
:param file_name:
:return:
"""
binary_str = ''
with open(file_name, 'r') as f:
for line in f:
binary_str += line.strip()
return binary_str
if __name__ == '__main__':
input_file = sys.argv[1]
print(binary_to_str(read_file(input_file)))
我正试图传入一个带有二进制消息的文本文件:
100100011001011101100110110011011110100000101011111011111110010110110011001000100001
它位于pythonprace文件夹中的文本文件binary1.txt以及binary_to_string.py文件中。
我从终端收到的错误如下:
bthib@bthib-cyberstorm ~ $ cd pythonpractice
bthib@bthib-cyberstorm ~/pythonpractice $ python ./binary_to_string.py > binary1.txt
/usr/bin/python: can't find '__main__' module in './binary_to_string.py'
最佳答案
错误//bash:。/binary_to_strong.py:没有这样的文件或目录:
是否在python脚本中提供了要调用的目录?
可以使用file对象将您想要的二进制值传递给textfile
关于python - 如何在python终端脚本中调用要使用的文本文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43086344/