简体   繁体   中英

Creating a text file with a variable as the name of the text file

I need to create a text file that stores the answers a user gives to a set of questions they are asked. This file needs to have a unique case number as its file name. The code below does that apart from the file isn't a text file, its file type just says "file".

The file needs to have the contents of the rnumber file as its file name. That is really important.

Does anyone know how this could be done?

def casenumberallocator(filename, answers, typeofdevice):
    os.chdir("H:\V4 Program\Questions")
    availablecasenumber = "not found"
    while availablecasenumber == "not found":
        rnumber = random.randint(1, 100)
        if rnumber in randomnumberlog:
            one = 1
        else:
            availablecasenumber = "found"
            randomnumberlog.append(rnumber)
    case = dict()
    case[rnumber] = {"Case number": rnumber,
               "Device": typeofdevice,
               filename: answers}
    casestring = ''.join('{}{}'.format(key, val) for key, val in case[rnumber].items())
    os.chdir("H:\V4 Program\Case_files")
    with open(str(rnumber), "w") as file: 
    #I have also tried str(rnumber).txt, and str(rnumber)".txt" but neither works. 
        file.write(casestring)
    os.chdir("H:\V4 Program")

You must "concatenate"...

open('"'+str(rnumber)+'.txt"', "w")

... I think...

感谢Stefano,对您的答案进行了稍微编辑后的版本有效。

open(str(rnumber)+'.txt'

You can also use string interpolation, which automatically converts the value to a string before inserting it.

"{}.txt".format(rnumber)

Or

"{}.{}".format(rnumber, "txt")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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