43

My python program has trouble opening a text file. When I use the basic open file for read, I get an ascii error. Someone helped me out by having me add an encoding parameter that works well in Idle, but when I run the program through terminal, I get this error message: "TypeError: 'encoding' is an invalid keyword argument for this function" How can I read this text file in to use it's data?

try:
    import tkinter as tk
    from tkinter import *
except:
    import Tkinter as tk
    from Tkinter import *

import time
import sys
import os
import random

flashcards = {}


def Flashcards(key, trans, PoS):
    if not key in flashcards:
        flashcards[key] = [[trans], [PoS]]
    else:
        x = []
        for item in flashcards[key][0]:
            x.append(item)
        x.append(trans)
        flashcards[key][0] = x
        x = []
        for item in flashcards[key][1]:
            x.append(item)
        x.append(PoS)
        flashcards[key][1] = x


def ImportGaeilge():
    flashcards = {}
    with open('gaeilge_flashcard_mode.txt','r', encoding='utf8') as file:
        for line in file:
            line1 = line.rstrip().split("=")
            key = line1[0]
            trans = line1[1]
            PoS = line1[2]
            Flashcards(key, trans, PoS)

def Gaeilge():
    numberCorrect = 0
    totalCards = 0
    ImportGaeilge()
    wrongCards = {}
    x = input('Hit "ENTER" to begin. (Type "quit" to quit)')
    while x != quit:
        os.system('cls')
        time.sleep(1.3)
        card = flashcards.popitem()
        if card == "":
## WRONG CARDS
            print ("Deck one complete.")
            Gaeilge()
        print("\n\n")
        print(str(card[0])+":")
        x = input("\t:")
        if x == 'quit':
            break
        else:
            right = False
            for item in card[1]:
                if x == card[1]:
                    right = True
                    print("\nCorrect!")
                    numberCorrect += 1
            if right == False:
                print(card[0])

        totalCards += 1
        print("Correct answers:", str(numberCorrect) +"/"+str(totalCards))


Gaeilge()

gaeilge_flashcard_mode.txt:

I=mé=(pron) (emphatic)
I=mise=(n/a)
you=tú=(pron) (subject)
you=tusa=(emphatic)
y'all=sibh=(plural)
y'all=sibhse=(emphatic)
he=sé=(pron)
he=é=(n/a)
he=seisean=(emphatic)
he=eisean=(n/a)
she=sí=(pron)
she=í=(n/a)
she=sise=(emphatic)
she=ise=(emphatic)
him=é=(pron)
him=eisean=(emphatic)
her=í=(pron)
her=ise=(emphatic)
her=a=(adj)

4 Answers 4

57

The terminal you are trying to run this on probably uses Python 2.x as standard.

Try using the command "Python3" specifically in the terminal:

$ Python3 yourfile.py

(Tested and confirmed that 2.7 will give that error and that Python3 handles it just fine.)

0
15

using io.open() instead of open removed this error for me eg:

import io
with io.open('gaeilge_flashcard_mode.txt','r', encoding='utf8') as file:
    for line in file:
        line1 = line.rstrip().split("=")
        key = line1[0]
        trans = line1[1]
        PoS = line1[2]
        Flashcards(key, trans, PoS)

reference: see this answer

4
  • 3
    This is your way to go if you are stuck with Python 2.x Jul 10, 2018 at 6:27
  • Why not overload using from io import open as open? Apr 15, 2022 at 12:26
  • 1
    it did not work for me :( Aug 2, 2022 at 1:10
  • adding io with encoding='utf8' worked for me, thanks
    – cem çetin
    Feb 7, 2023 at 15:14
4

+1 to The Unfun Cat for a correct answer regarding Linux etc.

For Windows users, however, calling 'Python3' generally won't work. But if you've installed Python 3.3 (or if you've downloaded and installed Python Launcher for Windows), you can type:

C:\scr>py -3 yourfile.py

Actually, this launcher also supports shebang syntax, so adding the following first line to your script's file will work fairly cross-platform (the /usr/bin is ignored on Windows):

#! /usr/bin/python3

After doing that, assuming that windows\py.exe is the default handler for .py files, you can just type:

C:\scr>yourfile.py

And if ".PY" is in your PATHEXT environment variable, you can just type:

C:\scr>yourfile

More info:

http://docs.python.org/3/whatsnew/3.3.html

http://www.python.org/dev/peps/pep-0397/

0

For code compatible with python 2 and 3:

import sys

if sys.version_info >= (3,0):
    with open("example.txt", encoding="utf-8") as rfile:
        long_description = rfile.read()
else: # encoding not compatible with python2
    with open("example.txt") as rfile:
        long_description = rfile.read()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.