【问题标题】:Splitting a Python Filename [duplicate]拆分 Python 文件名 [重复]
【发布时间】:2019-01-22 01:25:54
【问题描述】:

我正在尝试创建一个字谜程序测验。我所做的其中一件事是使用一种从指定文件中读取的中心方法,这取决于用户选择的选项,而不必重复代码。但是,当尝试将信息保存到文件时,保存的变量将路径文件保存在其中。如何拆分它以便它只保存已打开的文件的名称(即测验的名称)?

def main():
    name = input("Please Enter your name to begin")
    print("Hi",name,"Welcome to the Computer Science Quiz")
    user_choice = menu()
    option = choice(user_choice)
    option, counter = questions(option)
    update_file(name, option, counter)

def menu():
    print("Select from the following categories:")
    print("1 for System's Architecture, 2 for Memory, 3 for Storage or 4 for Network Topologies")
    choice = int(input("choose option"))
    if choice >0 and choice<=4: ## range check
        print("you have chosen",choice,)
    else:
        print("This is an invalid number")
        menu()      
    return choice

def choice(user_choice):
    if user_choice == 1:
        systems = open('systems.csv','r')
        return systems
    elif user_choice ==2:
        memory = open('memory.csv','r')
        return memory
    else:
        storage = open('storage.csv','r')
        return storage

def questions(option):
    counter = 0
    for line in option:
        anagrams = (line.rstrip("\n").split(","))
        question = anagrams[0]
        answer = anagrams[1]
        print (question)
        print (answer)
        guess = input("Enter your guess")
        if guess == answer:
            print("Well Done")
            counter = counter + 1
        else:
            print("oops")

    print("You have scored",counter,"correctly")
    return option,counter


def update_file(name, option, counter):
    string_counter = (str(counter))
    string_option = (str(option))
    results = [name,",",string_counter,",",string_option,"\n"]
    file = open('results.csv','a')
    file.writelines(results)
    file.close()

这是为选项变量保存文件时显示的内容: <_io.textiowrapper name="storage.csv" mode="r" encoding="cp1252">

【问题讨论】:

  • 你为什么不在choice() 中使用option='systems.csv',然后在question() 中使用with open(option, 'r') as f:
  • 谢谢凯文,我已经改变了它,它现在在文件中显示为 systems.csv。如何拆分文件名使其仅显示系统?
  • 这能解决您的问题吗?如果是这样,您可以搜索和研究更多有关python如何处理文件打开和关闭的信息,然后将您的问题更改为您真正想问的问题,然后自己回答问题。
  • 不完全,但它有助于了解文件中保存的信息。我正在尝试拆分结果文件中的文件名条目,以仅显示他们参加的测验的名称。所以目前,它在结果文件中显示 systems.csv,我希望它只显示系统。
  • 然后将option[:-4]os.path.splitext(option)[0] 而不是option 写入您的最终文件。对于后者,您需要先import os,这是一个更好的(通用)解决方案。

标签: python python-3.x filenames


【解决方案1】:

您可以使用此函数从文件名中删除路径:

import os
print(os.path.basename(file_name_with_path))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 2011-12-18
    相关资源
    最近更新 更多