我一直在尝试创建一个接受用户输入的函数,并使用该字符串重命名文本文件。我试过open("%x.txt" % name, "w")
,os.rename
.有没有我不知道的更有效的方法?
import os, sys, time
def textfile():
f = open("old.txt", "w")
x = input("name for your file: ")
os.rename("old.txt", "%x.txt)
f.write("This is a sentence")
f.close()
textfile()
你忘了实际格式化字符串。
import os, sys, time
def textfile():
f = open("old.txt", "w")
x = input("name for your file: ")
os.rename("old.txt", "{}.txt".format(x))
f.write("This is a sentence")
f.close()
textfile()
您无需打开文件即可重命名它。正如@Bryan Oakely所指出的,os.rename
是在Python中做到这一点的方法。例:
s = "old_name.txt"
x = input("name for your file: ")
os.rename(s,x+".txt")
将"old_name.txt"
重命名为任何x
(由用户指定),并以.txt
作为后缀。
避免使用input()
的一个好方法是:
import os, sys, time
def textfile():
x = raw_input("name for your file: ")
os.rename("old.txt", x + ".txt)
textfile()
在这里,您遇到了安全问题,因为您不限制输入。用户可以添加../hello.txt
并将文件写入另一个文件夹中。或者甚至做/etc/passwd
并将文件写在您可能不想写的地方。
这将起作用:
import os
def file_rename():
oldname=input("Old name: ") #Get the old file name, don't forget the extention
newname=input("New name: ") #Get the new file name (excluding the extention)
os.rename(oldname,newname + ".txt") #Renames the file
file_rename() #Calls the function above
如果您想重命名同一目录中的不同文件,这应该没问题,但是,如果不是将 oldname 输入设置为字符串,例如"example.txt"。