我需要将我的文件转换为ascii,大约有1000个文件,如果我一个接一个地做,那确实很耗时。
我是python的新手,我想做的就是将文件夹中的所有文件导入到数组中,以便我可以一次将它们全部转换。
答案 0 :(得分:0)
这应该在您要寻找的地方附近。
import os
import binascii
from sys import platform
# This was retrieved from the answer available at https://stackoverflow.com/questions/7396849/convert-binary-to-ascii-and-vice-versa
def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))
def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
n = int(bits, 2)
return int2bytes(n).decode(encoding, errors)
def int2bytes(i):
hex_string = '%x' % i
n = len(hex_string)
return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
def convert_files(path):
files = os.listdir(path)
for el in files:
with open(el, 'rb') as f:
result = text_from_bits(f.read())
if platform == "linux" or platform == "linux2":
with open("{}/{}.converted".format(path, el), 'a+') as f:
f.write(result)
elif platform == "win32":
with open("{}\{}.converted".format(path, el), 'a+') as f:
f.write(result)