试图访问位于闪存驱动器上的文件

Trying to access a file located on a flashdrive

我在 python 中做了一个简单的测试代码,它从一个文本文件中读取,然后在文本文件包含一行 "on".

时执行一个操作

如果我 运行 我的硬盘上的脚本与同一文件夹中的文本文件,我的代码工作正常。例如,(C:\Python27\my_file.txt 和 C:\Python27\my_scipt.py).

但是,如果我在我的文本文件位于我的闪存驱动器上并且我的脚本仍在我的硬盘驱动器上时尝试此代码,即使我指定了正确的路径,它也不会工作。例如,(G:\flashdrive_folder\flashdrive_file.txt 和 C:\Python27\my_scipt.py).

这是我写出来的代码。

    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

使用:

import os
os.chdir(path_to_flashdrive)

反斜杠字符有双重作用。 Windows用它作为路径分隔符,Python用它引入转义序列。

您需要转义反斜杠(使用反斜杠!),或使用以下其他技术之一:

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

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

    file = open("G:/flashdrive_folder/flashdrive_file.txt", "r")
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