Python脚本读取一行有空格并返回值

2024-09-28 15:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要读一行有const关键字和返回版本作为值。你知道吗

中的内容版本.php文件

final class Version
{
    /**
     * The current Piwik version.
     * @var string
     */
    const VERSION = '2.0.3';
}

这是我写的代码,但它没有返回任何东西。我做错了什么?你知道吗

def piwik_check(module):
    dirs = ["/var/www/piwik/core"]
    for dir_name in dirs:
        if os.path.exists(dir_name):
            readme_file = open("%s/Version.php" % dir_name)
            for line in readme_file.xreadlines():
                if line.startswith(str.strip("const")):
                    #version = str(line)
                    version = str(line).split()[1].strip()
                    return {'version': version}
                    break
                else:
                   continue
                readme_file.close()

Tags: name版本forversionvardirlinereadme
1条回答
网友
1楼 · 发布于 2024-09-28 15:27:26
with open(infile) as f:
    for line in f:
        if line.strip().startswith("const"):
             print(line.split()[3].rstrip(";"))
'2.0.3'

在您的功能中:

def piwik_check(module):
    dirs = ["/var/www/piwik/core"]
    for dir_name in dirs:
        if os.path.exists(dir_name):
            with open("{}/Version.php".format(dir_name)) as f:
                for line in f:
                    if line.strip().startswith("const"):
                        version = line.split()[3].rstrip(";")
                        return {"version":version} 

with自动关闭文件,版本号是拆分后的最后一个/第四个元素,如果您只想让版本号rstrip the;并简单地遍历file对象f。你知道吗

相关问题 更多 >