How can I rename files with a python script? - python

On my plone site I have hundreds of files (pdf, doc, ...) in filefield of archetypes objects. Something went wrong during importation and all the filenames are missing. The problem is that when somebody wants to open the file, since the extension is missing, the browser doesn't always propose to open it with a viewer.
The user has to save the file and add an extension to open it.
Can I write a python script to rename all files with an extension depending on the filetype?
Thank you.

http://plone.org/documentation/manual/plone-community-developer-documentation/content/rename
you've all you need here :)
The important part is this: parent.manage_renameObject(id, id + "-old")
you can loop over the subobjects doing:
for i in context.objectIds():
obj = context[i]
context.manage_renameObject(i, i + ".pdf")
context is the folder where you put this script, the folder where you've all your pdfs

The standard library function os.rename(src, dst) will do the trick. That's all you need if you know what the extension should be (e.g. all the files are .pdf). If you have a mixed bag of .doc, .pdf, .jpg, .xls files with no extensions, you'll need to examine the file contents to determine the proper extension using something like python-magic.
import os
for fn in os.listdir(path='.'):
os.rename(fn, fn + ".pdf")

Related

Iterating over .wav files in subdirectories of parent directory

Cheers everybody,
I need help with something in python 3.6 exactly. So i have structure of data like this:
|main directory
| |subdirectory's(plural)
| | |.wav files
I'm currently working from a directory where main directory is placed so I don't need to specify paths before that. So firstly I wanna iterate over my main directory and find all subdirectorys. Then in each of them I wanna find the .wav files, and when done with processing them I wanna go to next subdirectory and so on until all of them are opened, and all .wav files are processed. Exactly what I wanna do with those .wav files is input them in my program, process them so i can convert them to numpy arrays, and then I convert that numpy array into some other object (working with tensorflow to be exact, and wanna convert to TF object). I wrote about the whole process if anybody has any fast advices on doing that too so why not.
I tried doing it with for loops like:
for subdirectorys in open(data_path, "r"):
for files in subdirectorys:
#doing some processing stuff with the file
The problem is that it always raises error 13, Permission denied showing on that data_path I gave him but when I go to properties there it seems okay and all permissions are fine.
I tried some other ways like with os.open or i replaced for loop with:
with open(data_path, "r") as data:
and it always raises permission denied error.
os.walk works in some way but it's not what I need, and when i tried to modify it id didn't give errors but it also didnt do anything.
Just to say I'm not any pro programmer in python so I may be missing an obvious thing but ehh, I'm here to ask and learn. I also saw a lot of similiar questions but they mainly focus on .txt files and not specificaly in my case so I need to ask it here.
Anyway thanks for help in advance.
Edit: If you want an example for glob (more sane), here it is:
from pathlib import Path
# The pattern "**" means all subdirectories recursively,
# with "*.wav" meaning all files with any name ending in ".wav".
for file in Path(data_path).glob("**/*.wav"):
if not file.is_file(): # Skip directories
continue
with open(file, "w") as f:
# do stuff
For more info see Path.glob() on the documentation. Glob patterns are a useful thing to know.
Previous answer:
Try using either glob or os.walk(). Here is an example for os.walk().
from os import walk, path
# Recursively walk the directory data_path
for root, _, files in walk(data_path):
# files is a list of files in the current root, so iterate them
for file in files:
# Skip the file if it is not *.wav
if not file.endswith(".wav"):
continue
# os.path.join() will create the path for the file
file = path.join(root, files)
# Do what you need with the file
# You can also use block context to open the files like this
with open(file, "w") as f: # "w" means permission to write. If reading, use "r"
# Do stuff
Note that you may be confused about what open() does. It opens a file for reading, writing, and appending. Directories are not files, and therefore cannot be opened.
I suggest that you Google for documentation and do more reading about the functions used. The documentation will help more than I can.
Another good answer explaining in more detail can be seen here.
import glob
import os
main = '/main_wavs'
wavs = [w for w in glob.glob(os.path.join(main, '*/*.wav')) if os.path.isfile(w)]
In terms of permissions on a path A/B/C... A, B and C must all be accessible. For files that means read permission. For directories, it means read and execute permissions (listing contents).

Errno13, Permission denied when trying to read file

I have created a small python script. With that I am trying to read a txt file but my access is denied resolving to an no.13 error, here is my code:
import time
import os
destPath = 'C:\Users\PC\Desktop\New folder(13)'
for root, dirs, files in os.walk(destPath):
f=open(destPath, 'r')
.....
Based on the name, I'm guessing that destPath is a directory, not a file. You can do a os.walk or a os.listdir on the directory, but you can't open it for reading. You can only call open on a file.
Maybe you meant to call open on one or more of the items from files
1:
I take it you are trying to access a file to get what's inside but don't want to use a direct path and instead want a variable to denote the path. This is why you did the destPath I'm assuming.
From what I've experienced the issue is that you are skipping a simple step. What you have to do is INPUT the location then use os.CHDIR to go to that location. and finally you can use your 'open()'.
From there you can either use open('[direct path]','r') or destPath2 = 'something' then open(destPath2, 'r').
To summarize: You want to get the path then NAVIGATE to the path, then get the 'filename' (can be done sooner or not at all if using a direct path for this), then open the file.
2: You can also try adding an "r" in front of your path. r'[path]' for the raw line in case python is using the "\" for something else.
3: Try deleting the "c:/" and switching the / to \ or vice versa.
That's all I got, hope one of them helps! :-)
I got this issue when trying to create a file in the path -C:/Users/anshu/Documents/Python_files/Test_files . I discovered python couldn't really access the directory that was under the user's name.
So, I tried creating the file under the directory - C:/Users/anshu/Desktop .
I was able to create files in this directory through python without any issue.

How do I decide where to put the file while creating it in python?

With the code open, I can create a new file in the computer. How do i decide which folder it goes? I need to put them in a certain folder when i am creating them. Should I put sth in the brackets?
e.g. open("apple juice. txt", "a")
If you don't specify a path, then the file will be created in the current directory. Where exactly that is depends on how you started the interpreter. For example, when you start Python 3.4 from the Windows Start Menu, then the file will be saved in C:\Python34\.
If you want to specify a certain path, then do so:
f = open(r"C:\Users\David\Python Files\apple juice.txt", "a")
Give the full path:
with open("path_where/to_save/apple_juice.txt", "a") as f:
# do work
with will automatically close your file.
If you are looking for a place for temp files, use the module tempfile.
You can use the function tempfile.gettempdir() to get a path to a folder directory.
You can use tempfile.TemporaryFile() to generate a full path to the place where the temp files are usually stored on your OS.
The method used in either case to generate the temp path is explained here.

Tar function in Python

I am trying to tar a folder using the following code.
make_tarfile('logs_' + str(datetime.datetime.now()),logFolder)
def make_tarfile(output_filename, source_dir):
with closing(tarfile.open(output_filename, "w:gz")) as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
I dont see any tar file created though.Please could any one correct my code.
Thanks in advance
your code looks usable, you shall find the archive created.
be aware, the archive file name will be exactly the name, you pass into tarfile.open, you have to specify the extension .tar.gz if you want to see it as name of the archive.
the with closing is not necessary in Python 2.7+, you may use with tarfile.open(output_filename, "w:gz")) as tar: as open tarfile has proper context manager available.

Opening .out files in Python

Am I right in thinking Python cannot open and read from .out files?
My application currently spits out a bunch of .out files that would be read manually for logging purposes, I'm building a Python script to automate this.
When the script gets to the following
for file in os.listdir(DIR_NAME):
if (file.endswith('.out')):
open(file)
The script blows up with the following error "IOError : No such file or directory: 'Filename.out' "
I've a similar function with the above code and works fine, only it reads .err files. Printing out DIR_NAME before the above code also shows the correct directory is being pointed to.
os.listdir() returns only filenames, not full paths. Use os.path.join() to create a full path:
for file in os.listdir(DIR_NAME):
if (file.endswith('.out')):
open(os.path.join(DIR_NAME, file))
As an alternative that I find a bit easier and flexible to use:
import glob,os
for outfile in glob.glob( os.path.join(DIR_NAME, '*.out') ):
open(outfile)
Glob will also accept things like '*/*.out' or '*something*.out'. I also read files of certain types and have found this to be very handy.

Categories