gpt4 book ai didi

python - 如何调用要在我的 python 终端脚本中使用的文本文件

转载 作者:太空宇宙 更新时间:2023-11-04 12:31:51 27 4
gpt4 key购买 nike

我用 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

它位于我的 pythonpractice 文件夹中的文本文件 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脚本中给一个目录来调用?

可以使用文件对象将您想要的二进制值传递给文本文件

关于python - 如何调用要在我的 python 终端脚本中使用的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43086344/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com