[英]Python log filenames from a directory to a text file
I need help to make a python script that copies the names of the files in a certain directory and pastes them in a text file.我需要帮助制作一个 python 脚本来复制某个目录中的文件名并将它们粘贴到一个文本文件中。 The conditions are that If I delete a file from the directory the text file will still have the file name.条件是如果我从目录中删除一个文件,文本文件仍将具有文件名。 If I add a new file and ran the python script then it adds it to the list.如果我添加一个新文件并运行 python 脚本,那么它会将它添加到列表中。
what the directory looks like:目录是什么样的:
what the text file look like:文本文件的样子:
I solved the issue by using if x not in listfile
which checks if the string I am looking for is not in the text file.我通过使用if x not in listfile
解决了这个问题,它检查我要查找的字符串是否不在文本文件中。
import os
items = os.listdir(".")
newlist = []
for names in items:
newlist.append(names)
filename = open("filenames.txt")
listname = filename.readlines()
listname = [x.strip("\n") for x in listname]
filename.close()
store = open("filenames.txt","a")
for x in newlist:
if x not in listname:
store.write(x + "\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.