0

I'm pretty new to programming and I'm currently learning about the open() function used in python. My current goal is to create a to-do list, my first task was to create a filename in read mode otherwise if the file doesn't exist it is to be created in read/write mode "w+".

My current issue is the open() function isn't creating that empty "list.txt" which is the same folder where my code is saved into. I appreciate any feedback :)

def get_list(filename): 
    try: 
      f = open(filename, 'r')  # try to open the file in read mode 

    except:                      # if the file doesn't exist... 
      f = open(filename, 'w+') # create it by opening it in write

     
data = f.readlines()         # read the content of the file into a list 
f.close()                    # close the file 
return data                  # return data 
4
  • On your except block, try printing the exception. Maybe your python application doesn't have the permissions to create files on that folder. Commented Oct 12, 2022 at 3:09
  • After these edits, note that the get_list function returns None, not a file object. Indentation is important in python. Commented Oct 12, 2022 at 3:20
  • @CarlHR is there any way to check if the python application doesn't have permission to create files in that folder? Commented Oct 12, 2022 at 3:26
  • It depends on your current OS. On linux you could use the command ls -l to list all file and folder permissions, and use chown and chmod to alter any user / group permissions. If you're using Windows you can see which users are allowed to edit the current folder by clicking on it with the Right Mouse Button and clicking on the Properties option. Running the python script with sudo / admin privilege should fix the problem though. Commented Oct 12, 2022 at 3:32

1 Answer 1

1

You're almost there. You have to call the function you created with the Path where you would like the .txt file. The path is the location from the drive where it is stored. The following code is an example of what it should look like.

get_list('C:\Users\jsmith\list.txt')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.