创建一个文件夹,然后根据需要保存尽可能多的 .txt 文档
Posted
技术标签:
【中文标题】创建一个文件夹,然后根据需要保存尽可能多的 .txt 文档【英文标题】:Create a Folder then Save as many .txt Documents as I want 【发布时间】:2021-04-02 21:08:06 【问题描述】: import os
path = os.getcwd()
print(path)
y = False
while y == False:
dirName = input("Folder name: ")
try:
# Create target Directory
os.mkdir(dirName)
print("Directory '" , dirName , "' Created ")
y = True
except FileExistsError:
print("Directory " , dirName , " already exists")
folderDir = os.path.join(path, dirName)
y = int(input("Number of profs: "))
for a in range(y):
with open("number.txt","r") as z:
num = z.read()
num = int(num)
newNum = (int(num)+1)
numProf = ("profile"+str(newNum))
with open("number.txt","w") as file:
file.write(str(newNum))
file.close()
with open(folderDir+numProf+".txt","x") as f:
print(numProf)
###THIS DELETES THE FILES
##RESET FILE NUMBER
reset = input(str("Delete all files (Y/N)?"))
if reset == "y" or reset == "Y":
delete = True
if reset == "n" or reset == "N":
delete = False
if delete == True:
with open("number.txt","w") as file:
file.write("0")
file.close()
notRemoved = 0
removed = 0
for x in range(0,101):
try:
os.remove("profile"+str(x)+".txt")
removed += 1
except:
notRemoved +=1
print("Deleted "+str(removed))
这是代码^ Number 用于跟踪有多少文件。 不知道如何打开 number 来检查目录中有多少更改并保存在与 number.txt 相同的文件中,同时仍然创建一个新的空文件夹。
【问题讨论】:
与您的问题无关,但也许很高兴知道:您最好写if reset == "y" or reset == "Y":
而不是 if reset.lower() == "y":
但在您当前的情况下,如果您输入与“Y”、“y”、“N”、“n”(试试看)为避免这种情况,您可以立即写:delete = reset.lower() == "y"
这意味着,delete == True
如果重置为“y”(或“Y” ) 否则为假。为了执行检查,只需编写:if delete:
(delete == True
也可以,但在 python 世界中不常用/不经常使用)
also: reset = input(str("Delete all files (Y/N)?"))
也与 reset = input("Delete all files (Y/N)?")
相同。通常最好的做法是让文件尽可能短地打开并尽快关闭它们。这意味着,对于with open("number.txt","r") as z:
,您应该只保留下一行 (num = z.read()
) 的缩进,并且您可以将其后的所有其他行取消缩进 4(直到 ###THIS DELE...
注释)with open("number.txt","w") as file:
相同,只需保留该行在它缩进之后,去掉flle.close()
和其他人的身份。
您也不需要在另一个 with
语句中使用 file.close()
。离开with
声明后,文件将自动关闭。使用 python 编码快乐!
【参考方案1】:
folderDir = os.path.join(path, dirName,numProf)
with open(folderDir+".txt","x") as f:
print(folderDir+numProf)
更改了该代码并且它起作用了
【讨论】:
以上是关于创建一个文件夹,然后根据需要保存尽可能多的 .txt 文档的主要内容,如果未能解决你的问题,请参考以下文章