python-3.x - How to open a file using "filedialog.askopenfile" with "utf-8' encoding. I am able to open the file but it is opening with different encoding - TagMerge
2How to open a file using "filedialog.askopenfile" with "utf-8' encoding. I am able to open the file but it is opening with different encodingHow to open a file using "filedialog.askopenfile" with "utf-8' encoding. I am able to open the file but it is opening with different encoding

How to open a file using "filedialog.askopenfile" with "utf-8' encoding. I am able to open the file but it is opening with different encoding

Asked 1 years ago
0
2 answers

from tkinter import filedialog

filename = filedialog.askopenfilename()
with open(filename, 'r', encoding='utf8') as file:
    textfromfile = file.read()
    file.close()
print(textfromfile)

The sample above pops up a filedialog, lets you choose a file, loads the file in reading modus, with utf-8 encoding, and prints it to the console.

I used this workaround with filedialog.askopenfilename() because the filedialog.askopenfile() method scrambled some of the characters in my textfiles ('ë' among others).

Now it works fine, since the original texts I use are all utf-8 encoded.

Source: link

0

Check out this example,
# open a file
file_object = open('sample.txt')

# read the file content
data = file_object.read()

# print file content
print(data)

#close the file
file_object.close()
Python: Open a file using “open with” statement & benefits explained with examples Leave a Comment / FileHandling, Python / By Varun
This is a sample file.
It contains some sample string.
you are going to use it.
Thanks.
Python: Open a file using “open with” statement & benefits explained with examples Leave a Comment / FileHandling, Python / By Varun
FileNotFoundError: [Errno 2] No such file or directory: 'sample.txt'
Check out this code
# File is not closed in case of exception
try:
    # open a file
    file_object = open('sample.txt')
    # read file content
    data = file_object.read()
    # It will raise an exception
    x = 1 / 0
    print(data)
    file_object.close()
except:
    # Handling the exception
    print('An Error')
finally:
    if file_object.closed == False:
        print('File is not closed')
    else:
        print('File is closed')
Python: Open a file using “open with” statement & benefits explained with examples Leave a Comment / FileHandling, Python / By Varun
An Error
File is not closed

Source: link

Recent Questions on python-3.x

    Programming Languages