Create Empty File Using Python

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
with open(path, 'a'):
os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
os.makedirs(basedir)

python - creating an empty file and closing in one line

To be sure that the file is closed in any case, you can use the with statement. For example:

try:
with open(path_to_file, "w+") as f:
# Do whatever with f
except:
# log exception

Python create empty file - Unix

Well, for a start, the ones that rely on touch are not portable. They won't work under standard Windows, for example, without the installation of CygWin, GNUWin32, or some other package providing a touch utility..

They also involve the creation of a separate process for doing the work, something that's totally unnecessary in this case.

Of the four, I would probably use open('abc','a').close() if the intent is to try and just create the file if it doesn't exist. In my opinion, that makes the intent clear.

But, if you're trying to create an empty file, I'd probably be using the w write mode rather than the a append mode.

In addition, you probably also want to catch the exception if, for example, you cannot actually create the file.

Creating empty text files with specific names in a directory

You can use the module os to list the existing files, and then just open the file in mode w+ which will create the file even if you're not writing anything into it. Don't forget to close your file!

import os
for f in os.listdir(source_dir):
if f.endswith('.jpg'):
open(os.path.join(target_dir, f.replace('.jpg', '.txt')), 'w+').close()

Output is an empty file

First and foremost lets fix your paths, you imported from pathlib import Path but never used it.

lets declare infile = Path('/Users/name/Desktop/PDB/training_set_pssm/idlist/'), we now have some helpfull functions we can use for finding problems.

try out some of these to make sure you are searching in the right place.

#this will write out the absolute filepath usefull to check if it is correct
infile.absolute()

#this tells you if this path exists
infile.exists()

#this tells you if this is a file
infile.is_file()

let's start at the beginning
I'll try and explain what is happening in your code line by line.

if __name__ == '__main__':
# i don't really know what this infile is, is it a file containing
# d1s7za_.fasta.pssm
# d1s98a_.fasta.pssm
# d1s99a_.fasta.pssm

#or a directory containing files named
#d1s7za_.fasta.pssm
#d1s98a_.fasta.pssm
#d1s99a_.fasta.pssm
#...
infile = Path('/Users/name/Desktop/PDB/training_set_pssm/idlist')

# this returns a list of string presumably in the form of
# d1ciya2.fasta\n
# d1ciya3.fasta\n
# d1cq3a_.fasta\n
idlist = lines_to_list("/Users/name/Desktop/PDB/training_set_idlist")

# loop over that list
for ids in idlist:
# strips the '\n' from the id and adds '.pssm'
# you now have something like 'd1d0qa_.fasta.pssm'
# you never use this
part2 = ids.rstrip() + '.pssm'

# was 'if os.path.isfile(infile) == True:' but should be :
if infile.is_file():

# strips the '\n' from the id and adds '.profile'
# you now have something like 'd1d0qa_.fasta.profile'
ofile = ids.rstrip() + '.profile'

# here is where it becomes a bit weird
# in relevant_lines you say:
# Takes list (extracted from a .pssm file) and extracts the Sequence Profile Portion only.
# is infile a .pssm file?
# is this correct?
profile_list = relevant_lines(infile)

# this seems fine, it writes the normalized data to ofile.
# ofile will be something like 'd1d0qa_.fasta.profile'
write_normalized_profile(profile_list, ofile)

solution:

if __name__ == '__main__':
pssm_directory = Path('/Users/name/Desktop/PDB/training_set_pssm/idlist/') #the directory

idlist = lines_to_list("/Users/name/Desktop/PDB/training_set_idlist")

for ids in idlist:

infile = pssm_directory.joinpath(ids.rstrip() + '.pssm') #generate filename from id
if infile.is_file(): #check if filename exists

ofile = ids.rstrip() + '.profile'

profile_list = relevant_lines(infile)

write_normalized_profile(profile_list, ofile)

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()


Related Topics



Leave a reply



Submit