Get name of created file - python

I'm creating files in python and I want to print the full path of the already file created. Example:
dt = datetime.datetime.now()
datetime = dt.strftime("%d-%m")
output = open("c:\path\to\file_"+datetime+".txt","w")
How can I print the final name of the created file?
I tried:
print (output)
but it gives me a rare string.

For real file objects such as that,
print(output.name)

open() method doesn't return anything relevant. You can try on below methods...
1.print(output.__file__)
2. Import os
os.path.abspath("filename.ext"). # it will add the cwd to file name or if iterating the real path
os.path.dirname("filename.ext")
os.path.dirname("filename.ext")
3. Files= os.listdir(os.getcwd()) # it will list the files in cwd(you can give any path)
for i in files:
print(os.path.abspath(i))

Related

Whats the explanation for this behaviour?

from pathlib import Path
file = Path(r"C:\Users\SerT\Desktop\a.txt")
print (file.name)
file.rename(file.with_name("b.txt"))
print (file.name)
i'd like to know why file.name prints out "a.txt" in both instances even though the file actually gets renamed in windows explorer
The file is being renamed, but the original Path object (file in your case) is not changed itself.
Since Path.rename() returns a new Path object, to get the result you're expecting, do:
file = file.rename(file.with_name("b.txt"))
print(file.name)
.rename doesn't modify the file object, instead it simply returns the new filepath. If you want to rename a file, you can set file equal to the file.rename method:
import os
from pathlib import Path
file = Path(r"C:\Users\SerT\Desktop\a.txt")
print (file.name)
file = file.rename(file.with_name("b.txt"))
print(file.name)

Is there a way to remove part of a file name (path) in python?

I have around 50 files that have their name and then the date they were created at 3 times. How can I remove that part from the file name in python (You can show an example with other data it doesn't really matter)
I tried something like that:
file = 'directory/imagehellohellohello.png'
keyword = 'hello'
if (file.count(keyword) >= 3):
//functionality (here I want to remove the hello's from the file path)
This can be done quite simply using pathlib:
from pathlib import Path
path = Path("directory/imagehellohellohello.png")
target = path.with_name(path.name.replace("hello", ''))
path.rename(target)
And this indeed renames the file to "directory/image.png".
From Python version 3.8 the rename method also returns the new files' path as a Path object. (So it is possible to do:
target = path.rename(path.with_name(path.name.replace("hello", '')))
Methods/attributes used: Path.rename, Path.with_name, Path.name, str.replace
file = 'directory/imagehellohellohello.png'
keyword = 'hello'
if keyword*3 in file:
newname = file.replace(keyword*3, '')
os.rename(file, newname)

Creating folders based on a list read from a text file

I have some code as follows:
from sys import argv
import os;
home_dir = '/home/joga'
script, dirlist = argv
mylist = open(dirlist, 'r')
for folder in mylist:
newFolder = home_dir+'/'+folder
print "Folder name " +newFolder
if not os.path.exists(newFolder):
os.makedirs(str(newFolder))
os.chdir(newFolder)
mylist.close()
The idea is to read a list of folders listed in text file, and create each of these folders if they don't already exist. I am getting the folders created, however some have strange names, for example a stray '?' appended to the folder name
How do I fix this?
Answering my own question
I added a folder = folder.strip() as the first line in my for loop. I guess it line-ending was creating the junk character.

Python - create next file

I am writing a small script. The script creates .txt files. I do not want to replace existing files. So what I want python to do is to check if the file already exists. If it does not it can proceed. If the file does exists I would like python to increment the name and than check again if the file already exists. If the file does not already exist python may create it.
EXAMPLE:
current dir has these files in it:
file_001.txt
file_002.txt
I want python to see that the two files exists and make the next file:
file_003.txt
creating files can be done like this:
f = open("file_001.txt", "w")
f.write('something')
f.close()
checking if a file exists:
import os.path
os.path.isfile(fname)
If you want to check whether it's both a file and that it exist then use os.path.exists along with os.path.isfile. Or else just the former seems suffice. Following might help:
import os.path as op
print op.exists(fname) and op.isfile(fname)
or just print op.exists(fname)
Here is some code that will get the job done, I answered it myself.
import os.path
def next_file(filename):
"""
filename: string. Name only of the current file
returns: string. The name of the next file to be created
assumes the padding of the file is filename_001.txt The number of starting zeros does not not matter
"""
fill_exists = True
current = '001'
padding = len(current) # length of digits
file = '{}_{}.txt'.format(filename, current) # the actual name of the file, inlc. extension
while fill_exists:
if not os.path.isfile(file): # if the file does not already exist
f = open(file, 'w') # create file
f.write(filename)
f.close()
return 'Created new file: {}_{}.txt'.format(filename, current) # shows the name of file just created
else:
current = str(int(current)+1).zfill(padding) # try the next number
file = '{}_{}.txt'.format(filename, current)

creating a output file when the output file exists in the path

How do I code in python the option that when the output file exists in the path, the output file will automatically be "originalname"+"_1" / "originalname"+"_2" and so on ?
Something like
import os.path
def getnewfilename(filename):
testfile = filename
i = 0
while os.path.exists(testfile):
i += 1
testfile = "%s_%s" % (testfile, i)
return testfile
This should generate
filename
filename_1
filename_2
if you use %s_%3i" you should get
filename
filename_001
filename_002
filename_003
which will then list alphabetically (but have problems when i>=1000)
You can use os.path.exists to check if a file already exists. The rest is a simple loop that tries new filenames.
isfile checks for the existence of a file and goes down simlinks as well; you can use the full filepath.
if os.path.isfile(filename):
do_something()

Categories

Resources