How to convert binary files to text files in a list in Python 3?

隐身守侯 提交于 2021-02-10 08:36:42

问题


I'm trying to write a Python program that takes multiple binary files from LabView, selected and opened from a tkinter dialog box, and converts them to readable text files (or csv files, ideally). However, I'm having trouble with the binary to text conversion.

Things I've tried looking at the binascii module. It doesn't appear clear to me that you can use this module to convert multiple-page files, only short strings.

So, now, I'm thinking I should just open the file in utf-8 encoding and then read/write it in that encoding. Maybe this isn't the fastest or most robust route to go, but I've written a short code here:

from tkinter import Tk, filedialog  
root = Tk();
files = filedialog.askopenfilenames(parent=root,title='Choose a file')
print ('The tuple that represents your selected files is ', root.tk.splitlist(files))
fileslist = list(files)
print ('The list (mutable) that represents your selected files is ', fileslist)

for file in fileslist:
     with open(file, encoding="utf-8") as f:
         print (f.read())

I import tkinter, get a file dialog box, then convert the tuple of the multiple files I selected into a list. I notice, however, that the file is read as a string in my "for file in fileslist" for-loop. I'm not sure that's what I want. Anyways, any help solving the following would be much appreciated:

  1. Conversion of binary files to readable text files -- I know they are binary files, I'm unsure of the specific character encoding; if you open up the file in Wordpad, it has a b as the first character.
  2. Help creating a loop that saves the files selected after conversion in the same list from which they came so that the user can do further manipulation.

If I run my code as it stands, I get the following error output:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 371: invalid start byte

来源:https://stackoverflow.com/questions/51971671/how-to-convert-binary-files-to-text-files-in-a-list-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!