Modify .txt files, save originals and move modified - python

I modify many .txt files by adding string at the end of them.
How to save the original files and then move and rename modified ones?
I use os library.
i - iterated .txt files
new_name is variable consiting of random numbers
path=os.getcwd()
dirName=('new_directory')
This code only move files:
old_file = os.path.join(path, str(i))
new_path = os.path.join(path, dirName)
new_file = os.path.join(new_path, new_name)
os.rename(old_file, new_file)
I would like to use also os library to move and rename modified files.
Here is my whole code:
import os
import random
pressure=('Added pressure:')
dirName=('new_directory')
path=os.getcwd()
try:
os.mkdir(dirName)
print("Done: "+dirName)
except FileExistsError:
print("Directory" + dirName +" exist")
list=[]
for file in os.listdir("./"):
if file.endswith(".txt"):
lista.append(file)
for i in list:
f = open(i,"r")
file_contents = f.read()
print(f.read())
f.close()
if(pressure in file_contents):
print('It was added!')
else:
file=open(i, 'a')
rand_press=(str(random.randrange(980, 1040, 5))) #
rand_temp=(str(round(random.uniform(18, 26),2)))
press_and_temp=('Added pressure: \t'+rand_press+' mbar\n'+'Added temperature: \t'+rand_temp+' degC\n')
file.write(press_and_temp)
file.close()
new_name=str(rand_temp+'_'+rand_press+'.txt')
old_file = os.path.join(path, str(i))
new_path = os.path.join(path, dirName)
new_file = os.path.join(new_path, new_name)
os.rename(old_file, new_file)

Here are two suggestions.
1) Copy the file to a new location. Modify the second file. https://docs.python.org/3/library/shutil.html
2) Read the file, store it in some variable. Close the file. Create a new file in a new location, write to the file with your modifications, save it. https://www.guru99.com/reading-and-writing-files-in-python.html

Related

how to use element tree in this code to find a specific element

I have this code that moves all the jpegs, txts and xmls from one directory to another. i would like the create a loop that find a element inside the xml file and if it does exist it there, than it will move the file and if not it will keep the file in the directory. maybe someone can give me an advice?
this is my code so far:
import os
import glob
import shutil
def remove_ext(list_of_pathnames):
"""
removes the extension from each filename
"""
return [os.path.splitext(filename)[0] for filename in list_of_pathnames]
path = os.getcwd()
os.chdir("D:\\TomProject\\")
os.mkdir("Done") # create a new folder
newpath = os.path.join("D:\\TomProject\\", "Done") # made it os independent...
list_of_jpegs = glob.glob(os.path.join(path, '*.jpeg'))
list_of_xmls = glob.glob(os.path.join(path, '*.xml'))
list_of_txts = glob.glob(os.path.join(path, '*.txt'))
print(path)
print(list_of_jpegs, "\n\n", list_of_xmls, "\n\n", list_of_txts,
"\n\n") # remove
jpegs_without_extension = remove_ext(list_of_jpegs)
xmls_without_extension = remove_ext(list_of_xmls)
txts_without_extension = remove_ext(list_of_txts)
for filename in jpegs_without_extension:
if filename in xmls_without_extension:
if filename in txts_without_extension:
print("moving", filename) # remove
shutil.move(filename + '.jpeg', newpath) # move image to new path.
shutil.move(filename + '.xml', newpath)
shutil.move(filename + '.txt', newpath)

Find a directory containing desired text and stored all that files into another folder

How can we identify files of desired text in a file of the same directory and then separate all those files into another directory?
import os
user_input = input('What is the name of your directory')
directory = os.listdir(user_input)
searching = input('What word are you trying to find?')
for fname in directory:
if os.path.isfile(user_input + os.sep + fname):
# Full path
f = open(user_input + os.sep + fname, 'r')
if searching in f.read():
print('found string in file %s' % fname)
else:
print('string not found')
f.close()
shutil has many methods you can use. One of which is:
import shutil
shutil.copyfile(src, dst)
# 2nd option
shutil.copy(src, dst)
You can copy those file into another location.
by adding
if searching in f.read():
print('found string in file %s' % fname)
shutil.copy(user_input + os.sep + fname,destination)

Os.rename Files Overwrite

I am making a Python project that renames multiple files. However, sometimes the files overwrite.
suffixes = ['.pdf', '.epub', '.mobi']
file_list = []
def change_fname(dir_name, part=' (z-lib.org)', action='remove'):
fnames = os.listdir(dir_name)
for suffix in suffixes:
fnames_suffix = [f for f in fnames if f.endswith(suffix)]
for fname in fnames_suffix:
print(f'{action} "{part}" into/from "{fname}"')
if action == 'remove' and fname.endswith(part+suffix):
new_name = fname[:-len(suffix) - len(part)] + suffix
print(f'fname is {fname}')
elif action == 'insert':
new_name = fname[:-len(suffix)] + part + suffix
else:
raise Exception(f'Unknown Action: {action}')
print(new_name)
old_file = os.path.join(dir_name, fname)
new_file = os.path.join(dir_name, new_name)
os.rename(old_file, new_file)
file_to_show = '/Users/ChrisHart/Downloads/test i love you daddy/'
subprocess.call(["open", "-R", file_to_show])
if __name__ == '__main__':
dir_name = '/Users/ChrisHart/Downloads/test i love you daddy/'
try:
change_fname(dir_name, part=' (z-lib.org)', action='remove')
except Exception as ex:
print(ex)
This is my program ^
file (part).pdf
file.pdf
The file will delete " (part)", so we get this
file.pdf
file.pdf
And they overwrite.
file.pdf
How can I fix this overwriting?
I also wrote a script that changes multiple files. Maybe my code helps you understand your problem:
import os
print(os.getcwd()) #Gives you your current directory
os.chdir('/PATH/TO/FILES') #Change directory to the files
for i in os.listdir('/PATH/TO/FILES'):
os.rename(i, i.replace('(z-lib.org)', ' ')) #replaces z-lib with one whitespace
print(i)
I know what you're trying to replace :D ... I did the same thing

renaming the extracted file from zipfile

I have lots of zipped files on a Linux server and each file includes multiple text files.
what I want is to extract some of those text files, which have the same name across zipped files and save it a folder; I am creating one folder for each zipped file and extract the text file to it. I need to add the parent zipped folder name to the end of file names and save all text files in one directory. For example, if the zipped folder was March132017.zip and I extracted holding.txt, my filename would be holding_march13207.txt.
My problem is that I am not able to change the extracted file's name.
I would appreciate if you could advise.
import os
import sys
import zipfile
os.chdir("/feeds/lipper/emaxx")
pwkwd = "/feeds/lipper/emaxx"
for item in os.listdir(pwkwd): # loop through items in dir
if item.endswith(".zip"): # check for ".zip" extension
file_name = os.path.abspath(item) # get full path of files
fh = open(file_name, "rb")
zip_ref = zipfile.ZipFile(fh)
filelist = 'ISSUERS.TXT' , 'SECMAST.TXT' , 'FUND.TXT' , 'HOLDING.TXT'
for name in filelist :
try:
outpath = "/SCRATCH/emaxx" + "/" + os.path.splitext(item)[0]
zip_ref.extract(name, outpath)
except KeyError:
{}
fh.close()
import zipfile
zipdata = zipfile.ZipFile('somefile.zip')
zipinfos = zipdata.infolist()
# iterate through each file
for zipinfo in zipinfos:
# This will do the renaming
zipinfo.filename = do_something_to(zipinfo.filename)
zipdata.extract(zipinfo)
Reference:
https://bitdrop.st0w.com/2010/07/23/python-extracting-a-file-from-a-zip-file-with-a-different-name/
Why not just read the file in question and save it yourself instead of extracting? Something like:
import os
import zipfile
source_dir = "/feeds/lipper/emaxx" # folder with zip files
target_dir = "/SCRATCH/emaxx" # folder to save the extracted files
# Are you sure your files names are capitalized in your zip files?
filelist = ['ISSUERS.TXT', 'SECMAST.TXT', 'FUND.TXT', 'HOLDING.TXT']
for item in os.listdir(source_dir): # loop through items in dir
if item.endswith(".zip"): # check for ".zip" extension
file_path = os.path.join(source_dir, item) # get zip file path
with zipfile.ZipFile(file_path) as zf: # open the zip file
for target_file in filelist: # loop through the list of files to extract
if target_file in zf.namelist(): # check if the file exists in the archive
# generate the desired output name:
target_name = os.path.splitext(target_file)[0] + "_" + os.path.splitext(file_path)[0] + ".txt"
target_path = os.path.join(target_dir, target_name) # output path
with open(target_path, "w") as f: # open the output path for writing
f.write(zf.read(target_file)) # save the contents of the file in it
# next file from the list...
# next zip file...
You could simply run a rename after each file is extracted right? os.rename should do the trick.
zip_ref.extract(name, outpath)
parent_zip = os.path.basename(os.path.dirname(outpath)) + ".zip"
new_file_name = os.path.splitext(os.path.basename(name))[0] # just the filename
new_name_path = os.path.dirname(outpath) + os.sep + new_file_name + "_" + parent_zip
os.rename(outpath, new_namepath)
For the filename, if you want it to be incremental, simply start a count and for each file, go up by on.
count = 0
for file in files:
count += 1
# ... Do our file actions
new_file_name = original_file_name + "_" + str(count)
# ...
Or if you don't care about the end name you could always use something like a uuid.
import uuid
random_name = uuid.uuid4()
outpath = '/SCRATCH/emaxx'
suffix = os.path.splitext(item)[0]
for name in filelist :
index = zip_ref.namelist().find(name)
if index != -1: # check the file exists in the zipfile
filename, ext = os.path.splitext(name)
zip_ref.filelist[index].filename = f'{filename}_{suffix}.{ext}' # rename the extracting file to the suffix file name
zip_ref.extract(zip_ref.filelist[index], outpath) # use the renamed file descriptor to extract the file
I doubt this is possible to rename file during their extraction.
What about renaming files once they are extracted ?
Relying on linux bash, you can achieve it in a one line :
os.system("find "+outpath+" -name '*.txt' -exec echo mv {} `echo {} | sed s/.txt/"+zipName+".txt/` \;")
So, first we search all txt files in the specified folder, then exec the renaming command, with the new name computed by sed.
Code not tested, i'm on windows now ^^'

I am simply trying to write a python script that will change the filename in a directory of files

I am trying to create a script in python 2.7 that will rename all the files in a directory. Below is the code I have so far. The first function removes any numbers in the file name. The second function is supposed to rename the new file name. I get the following error when the second function runs:
[Error 183] Cannot create a file when that file already exists
I know this is because I am not looping through the files and adding an incrementing number to the new filename, so the script changes the name of the first file, and then tries to change the name of the second file to the same name as the first, producing the error.
Can someone help me create a loop that adds an incrementing number to each filename in the directory?
I tried adding:
if file_name == filename:
file_name = file_name + 1
in the while loop, but that obviously doesn't work because I cant concatenate an integer with a string.
import os
def replace_num():
file_list = os.listdir(r"C:\Users\Admin\Desktop\Python Pics")
print(file_list)
saved_path = os.getcwd()
print("Current Working Directory is " + saved_path)
os.chdir(r"C:\Users\Admin\Desktop\Python Pics")
for file_name in file_list:
print("Old Name - " + file_name)
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path)
replace_num()
def rename_files():
file_list = os.listdir(r"C:\Users\Admin\Desktop\Python Pics")
print(file_list)
saved_path = os.getcwd()
print("Current Working Directory is " + saved_path)
os.chdir(r"C:\Users\Admin\Desktop\Python Pics")
for new_name in file_list:
print("New Name - " + new_name)
try:
os.rename(new_name, "iPhone")
except Exception, e:
print e
rename_files()
instead of doing:
if file_name == filename:
file_name = file_name + 1
do something like this:
counter = 0
for file_name in file_container:
if file_name == file_name: # this will always be True - so it's unnecessary
file_name = "{0}_{1}".format(file_name, counter)
counter += 1

Categories