Home > Software design >  I want to save it by name i want
I want to save it by name i want

Time:11-09

I want to save by name i want

name = input("file name?")
copy = input("content?")
file = open(r"C:\Users\jikuma\Desktop\{}.txt", name, 'w', encoding='utf8')
file.write(copy)
file.close

I think the problem is "file = open(r"C:\Users\jikuma\Desktop\{}.txt", name, 'w', encoding='utf8')"

please answer or search keyword

CodePudding user response:

Your problem is that your path construction is faulty. Search for "Python format string". Python has several options to construct strings from other strings, such as:

r"C:\Users\jikuma\Desktop\"   name   ".txt"
r"C:\Users\jikuma\Desktop\%s.txt" % name
r"C:\Users\jikuma\Desktop\{}.txt".format(name)
rf"C:\Users\jikuma\Desktop\{name}.txt"

Your third line thus becomes

file = open(rf"C:\Users\jikuma\Desktop\{name}.txt", 'w', encoding='utf8')

Furthermore, when working with file paths, it is preferable to use os.path or pathlib:

import os
file = open(os.path.join(r"C:\Users\jikuma\Desktop", name   ".txt"), 'w', encoding='utf-8')

Besides, prefer to use context manager for opening files (i.e., the with keyword) to ensure the file is properly closed in every event:

import os
with open(os.path.join(r"C:\Users\jikuma\Desktop", name   ".txt"), 'w', encoding='utf-8') as file:
    file.write(copy)

CodePudding user response:

It will solve your issue,

file = open(r"C:\Users\jikuma\Desktop\%s.txt" %name, 'w', encoding='utf8')
  • Related