如何在Python中自动更新文件名列表
我有一个文件名列表:files=[untitled.txt,example.txt,alphabet.txt] 我还有一个创建新文件的功能:如何在Python中自动更新文件名列表,python,io,Python,Io,我有一个文件名列表:files=[untitled.txt,example.txt,alphabet.txt] 我还有一个创建新文件的功能: def create_file(file): """Creates a new file.""" with open(file, 'w') as nf: is_first_line = True while True: line = input("Line? (Type 'q' to quit.) ") if
def create_file(file):
"""Creates a new file."""
with open(file, 'w') as nf:
is_first_line = True
while True:
line = input("Line? (Type 'q' to quit.) ")
if line == "q":
# Detects if the user wants to quuit.
time.sleep(5)
sys.exit()
else:
line = line + "\n"
if is_first_line == False:
nf.write(line)
else:
nf.write(line)
is_first_line = False
我希望列表在创建文件后自动更新。但是,如果我只添加filename.append,
我意识到它只会在程序期间自我更新。有人知道怎么做吗?这在Python中可能吗?在Python中可能吗?->这与您选择的解决问题的语言的局限性无关。你想要的是坚持。您可以将文件列表存储在文本文件中。您的程序将在每次运行时读取内容,而不是在代码中硬编码列表 此代码可以帮助您开始: 使用openfiles.txt作为内嵌: files=[f.strip for f in infle.readlines] 打印文件:{files} 在这里做一些事情并创建文件“new_file” 新建文件='a_new_file.txt' files.appendnew\u文件 使用openfiles.txt,w作为输出文件: outfile.write\n.joinfiles
你当然可以。请看我的答案中添加的新示例。哦,是的!我忘了。谢谢示例代码将在每次运行期间在文件“files.txt”的末尾添加“a_new_file.txt”。要开始,请在单独的一行中创建文件files.txt,其中包含untitled.txt、example.txt和alphabet.txt。