Home > other >  Generation of files from list Linux / Python
Generation of files from list Linux / Python

Time:10-23

I have a list of file names in the single file record.txt as format like this:

/home/user/working/united.txt
/home/user/working/temporary.txt
/home/user/working/fruits.txt

I have the only temporary.txt file in the json format like temporary.json in the other folder which I needed as json

I want to create the all remaining files which are not in folder but present in list record.txt so that all the missing files are also there as blank files and at the end I have all three files. temporary.json has the data so I cannot generate all the files newly. Just the files which are missing in folder and present in list. At the end, I want to get like below by python or shell script.

united.json 
temporary.json
fruits.json

and temporary.json still has data

CodePudding user response:

This command with "create" the files w/o erasing existing ones:

while read i ; do touch "${i%.*}.json"; done<record.txt

The modification time of temporary.json will change to the current one

CodePudding user response:

in Python, you can use os.path.isfile to check if a file exist and then create with open(filename,'w'):

from os.path import isfile
_createTxtFlag = True
_createJSONFlag = True


with open('temporary.txt') as fil:
    for l in fil.readlines():
        l = l.rstrip() #to remove end of line
        #create .txt files if not exists
        if _createTxtFlag:
            if not isfile(l):
                with open(l,'w') as newFil:
                    pass
        if _createJSONFlag:
            json_name = f"{l.split('.')[0]}.json"
            if not isfile(json_name):
                with open(json_name,'w'):
                    pass
  • Related