简体   繁体   English

在python脚本中打开文件夹和文件

[英]Opening folders and files in python scripting

I have this piece of code: 我有这段代码:

import os
def find(name):
    for root, dirs, files in os.walk("Desktop/"):
        if name in files:
             os.startfile("Desktop/", name, ".exe")


def findFold(name):
    for root, dirs, files in os.walk("Desktop/"):
        if name in files:
            os.startfile("This PC/", name)

..............
    if OpenFile.lower() == "music" or OpenFile.lower() == "music folder":
        findFold("Music")
..............
    elif OpenFile.lower() == "wolf team" or OpenFile.lower() == "wolfteam":
        find("Wolfteam")

The OpenFile is a string which is the input of the user(the name of the file or folder. OpenFile是一个字符串,它是用户的输入(文件或文件夹的名称。
The program doesn't open the files and folders that I want it to open. 该程序无法打开我要打开的文件和文件夹。

I looked in the internet and this is how people said it is and working.. Can somebody help please? 我看了看互联网,这就是人们所说的那样,正在工作。有人可以帮忙吗?

It is very unclear of what you are trying to accomplish, however, I believe you have a backslash where you want a forward slash if you are trying to invoke applications on a Windows based file system 目前尚不清楚您要完成的工作,但是,我认为如果您尝试在基于Windows的文件系统上调用应用程序,则需要在正斜杠处加反斜杠

eg I would change 例如,我会改变

os.startfile("This PC/", name)

to

os.startfile("This PC/{}".format(name))

I also suggest you look into the PEP 8 coding conventions for Python, and use their suggestions for readable code. 我还建议您研究适用于Python的PEP 8编码约定,并将其建议用于可读代码。 Namely: 即:

look into adding docstrings to your methods 研究向您的方法添加文档字符串

def fileFold(name):
    '''
    why this method exists
    '''

do not hard code your paths but have them be variables 不要对路径进行硬编码,而应将其作为变量

def findFold(name, prefix="\Desktop\", suffix=".exe")

wrap your activities in Try Except blocks 将活动包装在“尝试除外”块中

try:
    os.startfile("{}{}{}".format(prefix, name, suffix))
except OSError as err:
    print("Unable to invoke application {}: {}".format(name, err))

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

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