简体   繁体   English

从任何目录打开文件

[英]Opening Files From Any Directory

I'm writing this basic code that runs files on my computer but right now it can only open files from the directory it is in. is there a way to open files from anywhere on my computer or would I have to give the path for the file. 我正在编写这个在我的计算机上运行文件的基本代码,但是现在它只能从它所在的目录中打开文件。有没有办法从我的计算机上的任何地方打开文件,或者我必须给出路径文件。

Here is my code: 这是我的代码:

def run(filename):
    try:
        import os
        os.startfile(filename)
    except:
        WindowsError
        print ("Thats not a valid file name")

while True:

    filename = raw_input("Filename: ")
    run(filename)
    x = raw_input("Would you like to open another file? [y/n]: ")
    if x == "n":
        quit()

This opens and runs the files fine but only from the directory its saved in. 这将打开并运行文件,但只能从保存的目录中运行。

you can do this a couple of different ways 你可以用几种不同的方式做到这一点

either use entire paths 要么使用整个路径

or change the directory its looking at 或者更改它所看到的目录

changing the directory is pretty easy 更改目录非常简单

os.chdir("PATH TO DIRECTORY")
def run(filename):
    for directoy,files,dirs in os.walk("C:\\"):
        if filename in files:
           return os.startfile(os.path.join(directory,filename))

fair warning it may be slow ... 公平警告可能会很慢......

Can you try it: 你能试试吗:

import os
def run(filename):
    if not os.path.exists(filename):
       print("Thats not a valid file name")
       return
    if os.path.isfile(filename):
       # Your code here
    elif os.path.isdir(filename):
       # Your code here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM