Python - create next file - python

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)

Related

Get name of created file

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

Find files that had been stored from a single text file

Is there any way for me to read file that I saved inside a text file using python?
For example I have a file called filenames.txt. The content of the file should have name of other files such as:
/home/ikhwan/acespc.c
/home/ikhwan/trloc.cpp
/home/ikhwan/Makefile.sh
/home/ikhwan/Readme.txt
So, theoretically what I want to do is I have a Python script to change some header of the file. So filenames.txt will act as a platform for me whenever I want to run the script to change only selected file. The reason is I have so many files inside directory and subdirectories and I just want python to read only the files that I put inside filenames.txt and only change that particular file. In the future, if I want to run the script on other files, I just can add or replace filenames in filenames.txt
So the flow of the script will be as follows:
Run script-->script start search for the filenames inside filenames.txt-->script will add or change header of the file.
Current, i used os.walk but it will search within all directory and subdirectory. Here are my current function.
def read_file(file):
skip = 0
headStart = None
headEnd = None
yearsLine = None
haveLicense = False
extension = os.path.splitext(file)[1]
logging.debug("File extension is %s",extension)
type = ext2type.get(extension)
logging.debug("Type for this file is %s",type)
if not type:
return None
settings = typeSettings.get(type)
with open(file,'r') as f:
lines = f.readlines()
You don't need to walk through the file system if you already have your file paths listed in the filenames.txt, just open it, read it line by line and then process each file path from it, e.g.
# this is your method that will be called with each file path from the filenames.txt
def process_file(path):
# do whatever you want with `path` in terms of processing
# let's just print it to STDOUT as an example
with open(path, "r") as f:
print(f.read())
with open("filenames.txt", "r") as f: # open filenames.txt for reading
for line in f: # read filenames.txt line by line
process_file(line.rstrip()) # send the path stored on the line to process_file()

Python3 Walking A Directory and Writing To Files In That Directory

I have created a script that writes the binary content of my files to other files in the same directory that end with a certain extension. When doing this however I have come onto an issue, when I open the file and save the new file in a folder, it creates a new file. I'll show an example. There is a folder, FOLDER1 with test.py inside, inside the folder is a folder called OPTION1 with the files, bye.sh and hello. When I try to execute test.py, my program sees the files bye.sh and hello(hello's binary data is being copied to bye.sh) in OPTION1 and reads it, but creates a new file in the FOLDER1 alongside test.py creating a new bye.sh in FOLDER1, how do I make it overwrite the bye.sh in OPTION1? Just mentioning, I am running Mac OS X.
Code here:
import os
class FileHandler:
#import all needed modules
def __init__(self):
import os
#Replaces second file with the binary data in file one
"""
Trys To Check If a File Exists
If It exists, it will open the file that will be copied in binary form and the output file in reading/writing binary form
If the input file doesnt exist it will tell the user, then exit the program
Once the files are open, it reads the input file binary and copies it to the output file
Then it checks to see if the two binaries match which they should if it all worked correctly, the program will then return true
The Files are then closed
If it failed to try it will tell the user the file was skipped
"""
def replaceBinary(self,file_in="",file_out=""):
try:
if(os.path.isfile(file_in)):
in_obj = open(file_in,"rb") #Opens The File That Will Be Copied
out_obj = open(file_out,"wb+") #Opens The File That Will Be Written To
object_data = in_obj.read()#Get Contents of In File
out_obj.write(object_data)# Write Contents of In File To Out File
print("SPECIAL FILE:"+file_out)
print(os.getcwd())
if out_obj.read() == in_obj.read():
print("Its the same...")
return True
print("Done Copying...")
else:
print("Usage: Enter an input file and output file...")
print(file_in+" Doesn't Exist...")
raise SystemExit
return False
in_obj.close()
out_obj.close()
except:
print("File, "+file_out+" was skipped.")
"""
Procedurally continues down an entire location and all its locations in a tree like manner
Then For each file found it checks if it matches of the extensions
It checks a file for the extensions and if it has one of them, it calls the replace binary function
"""
def WalkRoot(self,file1="",root_folder=""):
for root,dirs,files in os.walk(root_folder):
for f in files:
print(os.path.abspath(f))
array = [".exe",".cmd",".sh",".bat",".app",".lnk",".command",".out",".msi",".inf",".com",".bin"]
for extension in array:
if(f.endswith(extension)):
print("Match|\n"+os.path.abspath(f)+"\n")
self.replaceBinary(file1,os.path.abspath(f))
break #If The right extension is met skip rest of extensions and move to next file
print("Done...")
def main():
thing = FileHandler()
#path = os.path.join(os.getcwd())
path = input(str("Enter path:"))
thing.WalkRoot("Execs/hello","/Users/me/Documents/Test")
main()
Thanks!
The list of files returned by os.walk() does not include directory information. However, the dirpath (which you call root) is updated as you go through the list. Quoting the manual,
filenames is a list of the names of the non-directory files in dirpath. Note
that the names in the lists contain no path components. To get a full path
(which begins with top) to a file or directory in dirpath, do
os.path.join(dirpath, name).[1]
So, to get the correct, full path to the files within your top-level directory, try replacing
self.replaceBinary(file1,os.path.abspath(f))
with
self.replaceBinary(file1, os.path.join(root, f))
[1] https://docs.python.org/3.5/library/os.html#os.walk

Python3 Rename files in a directory importing the new names from a txt file

I have a directory containing multiple files.
The name of the files follows this pattern 4digits.1.4digits.[barcode]
The barcode specifies each file and it is composed by 7 leters.
I have a txt file where in one column I have that barcode and in the other column the real name of the file.
What I would like to do is to right a pyhthon script that automatically renames each file according to the barcode to it s new name written in the txt file.
Is there anybody that could help me?
Thanks a lot!
I will give you the logic:
1. read the text file that contains barcode and name.http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python.
for each line in txt file do as follows:
2. Assign the value in first(barcode) and second(name) column in two separate variables say 'B' and 'N'.
3. Now we have to find the filename which has the barcode 'B' in it. the link
Find a file in python will help you do that.(first answer, 3 rd example, for your case the name you are going to find will be like '*B')
4. The previous step will give you the filename that has B as a part. Now use the rename() function to rename the file to 'N'. this link will hep you.http://www.tutorialspoint.com/python/os_rename.htm
Suggestion: Instead of having a txt file with two columns. You can have a csv file, that would be easy to handle.
The following code will do the job for your specific use-case, though can make it more general purpose re-namer.
import os # os is a library that gives us the ability to make OS changes
def file_renamer(list_of_files, new_file_name_list):
for file_name in list_of_files:
for (new_filename, barcode_infile) in new_file_name_list:
# as per the mentioned filename pattern -> xxxx.1.xxxx.[barcode]
barcode_current = file_name[12:19] # extracting the barcode from current filename
if barcode_current == barcode_infile:
os.rename(file_name, new_filename) # renaming step
print 'Successfully renamed %s to %s ' % (file_name, new_filename)
if __name__ == "__main__":
path = os.getcwd() # preassuming that you'll be executing the script while in the files directory
file_dir = os.path.abspath(path)
newname_file = raw_input('enter file with new names - or the complete path: ')
path_newname_file = os.path.join(file_dir, newname_file)
new_file_name_list = []
with open(path_newname_file) as file:
for line in file:
x = line.strip().split(',')
new_file_name_list.append(x)
list_of_files = os.listdir(file_dir)
file_renamer(list_of_files, new_file_name_list)
Pre-assumptions:
newnames.txt - comma
0000.1.0000.1234567,1234567
0000.1.0000.1234568,1234568
0000.1.0000.1234569,1234569
0000.1.0000.1234570,1234570
0000.1.0000.1234571,1234571
Files
1111.1.0000.1234567
1111.1.0000.1234568
1111.1.0000.1234569
were renamed to
0000.1.0000.1234567
0000.1.0000.1234568
0000.1.0000.1234569
The terminal output:
>python file_renamer.py
enter file with new names: newnames.txt
The list of files - ['.git', '.idea', '1111.1.0000.1234567', '1111.1.0000.1234568', '1111.1.0000.1234569', 'file_renamer.py', 'newnames.txt.txt']
Successfully renamed 1111.1.0000.1234567 to 0000.1.0000.1234567
Successfully renamed 1111.1.0000.1234568 to 0000.1.0000.1234568
Successfully renamed 1111.1.0000.1234569 to 0000.1.0000.1234569

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