How to find a file within the same folder of a .py

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ciremo
    New Member
    • May 2010
    • 1

    How to find a file within the same folder of a .py

    I've made a simple script which asks questions, and writes the answers into a file (Answers.txt) However, the only way I get it to work is to define the entire path, e.g. C:\folder\Answe rs.txt

    But Answers.txt can be in different folders depending on where users have installed it, so I'm wondering if I can make the script search within its own folder? That way people would be able to simply place the two in the same folder and not have to rewrite the pathing.

    I tried simply writing into \Answers.txt but it didn't work. It seems to find the file, but doesn't write to it.
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    You want to always use the complete path. It will avoid a lot of needless debugging over the years. The simplest solution if I understand, would be to append the person's name to the file name, "Answers_Bob.tx t", and store them all in the same directory.

    Comment

    • Motoma
      Recognized Expert Specialist
      • Jan 2007
      • 3236

      #3
      To write to a file in the current working directory (the directory the user is currently in) you would just write to 'Answers.txt'.

      To write to the directory that the script is in, you would write to os.join(sys.pat h[0], 'Answers.txt')

      Comment

      • Glenton
        Recognized Expert Contributor
        • Nov 2008
        • 391

        #4
        If it finds the file and doesn't write to it, then the problem is not the path! open("answers.t xt","w") is what you need if you want to over-write the file each time. Or "a" to append. Or "r" to read-only (this is the default), which is why I suspect you were using open("answers.t xt").

        Comment

        Working...