-1

I have a txt file with data like this:

AL Autauga

AL Baldwin

AL Barbour

AL Bibb

def stateToCounties(filename):

    """
    :param filename: text containing state name, tab, county name, enter button...
    :return: { state name : [list of counties in that state] }
    """

    filein = open(filename.txt, 'r')
    lines = filein.readlines()
    rawdata = []
    states = {}

    for line in lines:
        line = line.strip('\n').split('\t')
        rawdata += [line]

    filein.close()

    for part in rawdata:
        if part[0] not in states.keys():
            states[part[0]] = [part[1]]
        else:
            states[part[0]] += [part[1]]
    return states


print(stateToCounties('uscounties.txt'))

I should be getting something like {'AL': [Autauga...]} as my output but instead got an error: AttributeError: 'str' object has no attribute 'txt'. If I use the line filein = open('filename.txt', 'r') as opposed to filein = open(filename.txt, 'r') then I get FileNotFoundError: [Errno 2] No such file or directory: 'filename.txt' as an error. How can I rectify this? The file is in the same folder as my .py file and I have read in files like this before so I don't understand what's wrong now.

  • You either mean: filein = open(filename, 'r') or filein = open(filename + ‘.txt’, 'r') – quamrana Apr 26 '20 at 19:35
  • The fact, that the file is in the same folder as your script is irrelevant. Python looks for the file in the current working directory and that doesn't have to be the same as the directory where your script is located. Use an absolute path. You can find the path of the script with `pathlib`: `pathlib.Path(__file__).parent` (and add the filename itself with `pathlib.Path(__file__).parent / filename`) – Matthias Apr 26 '20 at 20:07

1 Answers1

2

Aha, you don't need filename.txt. in stead just do

filein = open(filename, 'r')

filename - the variable input to the function is already a string object and it contains its extension .txt. You can't do .txt on a string object. If you want to pass on the filename without extension to the function, then while opening the file later, you need to do :

filein = open(f'{filename}.txt', 'r')
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
  • I tried ```filein = open(f'{filename}.txt', 'r')``` and got FileNotFoundError: [Errno 2] No such file or directory: 'uscounties.txt'. Then I tried ```filein = open(filename, 'r') ```and got FileNotFoundError: [Errno 2] No such file or directory: 'uscounties'. –  Apr 26 '20 at 19:49
  • 1
    @Orla You need to give proper filepath. When you try to do `open(only_file_name, 'r')` python assumes that file is in the current directory. You need to give either absolute path or path relative to this script, not the file name only. – Arkistarvh Kltzuonstev Apr 26 '20 at 19:52
  • I creates a new .py file in the same folder I have the original one in and copied and pasted my code, suddenly its working perfectly - do you think there was a problem with the initial file? –  Apr 26 '20 at 20:42