简体   繁体   中英

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. 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.

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.

    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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM