0

I have made a simple test code in python that reads from a text file, and then preforms an action if the text file contains a line "on".

My code works fine if i run the script on my hardive with the text file in the same folder. Example, (C:\Python27\my_file.txt, and C:\Python27\my_scipt.py).

However, if I try this code while my text file is located on my flashdrive and my script is still on my hardrive it won't work even though I have the correct path specified. Example, (G:\flashdrive_folder\flashdrive_file.txt, and C:\Python27\my_scipt.py).

Here is the code I have written out.

    def locatedrive():
        file = open("G:\flashdrive_folder\flashdrive_file.txt", "r")
        flashdrive_file = file.read()
        file.close()

        if flashdrive_file == "on":
            print "working"

        else:
            print"fail"


    while True:
        print "trying"
        try:
            locatedrive()
            break
        except:
            pass
            break
Lee Denbigh
  • 80
  • 1
  • 5
RatstabOfficial
  • 479
  • 2
  • 8
  • 14
  • I found out if the file is in the root folder of the flashdrive my code works fine. Example, "G:\my_file.txt", but if the file is in a folder I get an error. Example, "G:\my_folder\my_file.txt" The error I get is, "IOError: [Errno 22] invalid mode ('r') or filename: 'G:\my_folder\\my_file.txt' – RatstabOfficial May 09 '15 at 03:22
  • i've not tred it yet, but i think `\\` should be `/` or use `\\\` – Dyno Fu May 09 '15 at 03:24

3 Answers3

3

The backslash character does double duty. Windows uses it as a path separator, and Python uses it to introduce escape sequences.

You need to escape the backslash (using a backslash!), or use one of the other techniques below:

    file = open("G:\\flashdrive_folder\\flashdrive_file.txt", "r")

or

    file = open(r"G:\flashdrive_folder\flashdrive_file.txt", "r")

or

    file = open("G:/flashdrive_folder/flashdrive_file.txt", "r")
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0
cd /media/usb0
import os

path = "/media/usb0"

#!/usr/bin/python
import os

path = "/usr/tmp"

# Check current working directory.
retval = os.getcwd()
print "Current working directory %s" % retval

# Now change the directory
os.chdir( path )

# Check current working directory.
retval = os.getcwd()

print "Directory changed successfully %s" % retval
Pang
  • 9,564
  • 146
  • 81
  • 122
-1

Use:

import os
os.chdir(path_to_flashdrive)
Abhishek Dey
  • 1,601
  • 1
  • 15
  • 38