file rename, python batch-processing [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm new to coding, and only know VBA at best.
However I would like a python script which will rename all the excel files in a folder. It needs to include the date the file was last modified at the start of the string. The date format will be YYYYMMDD.
For example, if the original file name is "CWI001-CA-E1140", the ammended file name should be "20150422_CWI001-CA-E1140".
I'm using windows 8, thanks in advance.

Using os.listdir to get a list of file in a directory, and os.rename to rename files.
import datetime
import os
DIRECTORY = '.'
for filename in os.listdir(DIRECTORY):
# Skip non-xls file
if not filename.lower().endswith('.xls'):
continue
path = os.path.join(DIRECTORY, filename)
mtime = os.path.getmtime(path) # modification time
prefix = datetime.datetime.fromtimestamp(mtime).strftime('%Y%m%d')
newpath = os.path.join(DIRECTORY, prefix + '_' + filename)
# rename it
os.rename(path, newpath)

Related

a problem with shutil: the code won't work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 hours ago.
Improve this question
import os
import shutil
source = r'/Users/***/Downloads/test1'
destination = r'/Users/***/Downloads/test2'
files = os.listdir(source)
files2 = os.listdir(destination)
for file in files:
if os.path.isfile(file):
shutil.copy(file, destination)
It just doesn't copy anything. It worked but then just crashed or smth. Now it doesn't say that there's any mistake in the code, but it doesn't do anything
Try this to debug your code
import os
import shutil
source = r'/Users/***/Downloads/test1'
destination = r'/Users/***/Downloads/test2'
files = os.listdir(source)
files2 = os.listdir(destination)
print("files:",files)
for file in files:
print("Testing whether ", file, " is a file")
if os.path.isfile(file):
print("Yes, so attempting to copy file", file)
shutil.copy(file, destination)
It will help you see a clearer picture of what is going wrong. If you can reply with the information printed when you run it, that will help people find the problem.

How do I read the pictures in the file in order? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
I want to read the pictures in a file in the order they are in the file. But when I read it with python it reads mixed. I don't want it sorted. How can I fix this?
def read_img(path):
st = os.path.join(path, "*.JPG")
st_ = os.path.join(path, "*.jpg")
for filename in glob.glob(st):
print(st)
#print("filename-------",filename)
img_array_input.append(filename)
print("image array append : ", filename)
for filename in glob.glob(st_):
img_array_input.append(filename)
#print("filename-------",filename)
global size
size = len(img_array_input)
for i in img_array_input:
print("detection ")
detection(i)
print("detection out")
enter image description here
original file
enter image description here
the order of reading
I want it to read in the order in the original file.
If you want the list populated in the order that os.listdir() reveals files then:
from os import listdir
from os.path import join, splitext
BASE = '.' # directory to be parsed
EXTS = {'jpg', 'JPG', 'jpeg', 'JPEG'} # file extensions of interest
def ext(p):
_, ext = splitext(p)
if ext:
return ext[1:]
def getfiles(base, include_base=True):
for entry in listdir(base):
if ext(entry) in EXTS:
yield join(base, entry) if include_base else entry
detection = [file for file in getfiles(BASE, include_base=False)]
print(detection)
Note:
os.listdir() returns a list of files in arbitrary order

I couldn't make a list with these codes in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I couldn't make a list with these codes in python
import os
path = r'C:\Users\fabri\Downloads\arquivos'
extension = '.csv'
for root, dirs_list, files_list in os.walk(path):
for file_name in files_list:
if os.path.splitext(file_name)[-1] == extension:
file_name_path = os.path.join(root, file_name)
print(file_name_path)
Use glob.glob() with the recursive=True option to get all the matching files in a folder and its subfolders.
from glob import glob
path = r'C:\Users\fabri\Downloads\arquivos'
file_list = glob.glob(os.path.join(path, '**/*.csv'), recursive=True)

how to get a file path with the name and the kind of the file using python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
so I am getting a name of and I know it's an EXE file.
I need to get the path which the file is at.
It could be anywhere in the computer.
Is there a muddle for it? or a simple script that I am missing?
import os
files = os.listdir(path='.') # getting all files in currect directory
def get_path(files):
filename = ""
for file in files:
if file == "main.py": # replace "filename.exe" with the name of the file
filename = file # saving the name of the file in a variable
break
elif re.match(r"^\.", file):
get_path(os.listdir(file))
absolute_path = os.path.abspath(filename) # absolute path to the file
return absolute_path
print(get_path(files))
You can try to use os.walk()
import os
file_name = 'the_file_to_find.exe'
for root, _, files in os.walk('\\'):
if file_name in files:
print(os.path.join(root, file_name))
break
However, searching in the whole '\' can be slow, so it would be better to be more precise.

Python: How can I open and read files in a directory that do not have a file extension (Windows)? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am currently in the process of writing a script that will parse a file for a specific string and rename the file to that string. However, the files that this script will be dealing with do not have file extensions. They are readable in any text editor, but they do not have a file type other than the generic "FILE" type in their properties window.
I have tried researching this for a few days now and have been unsuccessful in finding any documentation specific to my problem. So is there any python method of opening, reading, renaming, and saving a file that has no specified file extension?
You can open() or os.rename() all files that you have access to. It doesn't matter if it doesn't have an extension.
If you don't know which files to rename, then just open all files, read their contents and act on the files that match what you're looking for.
import os
# Get a list of all files under the current directory
flist = []
for root, dirs, files in os.walk('.'):
flist += [os.path.join(root, f) for f in files]
# Go over each file and see if it contains the string foo
want = 'foo'
targets = []
for path in flist:
with open(path) as df:
data = df.read()
if want in data:
targets.append(path)
# The targets list now contains the paths of all the files that contain foo.
Have a look at this answer.
When you iterate through the list of files you can simply check if the extension is empty.
def file_has_no_extension(file_path):
"""
Return true if and only if the file has no extension.
"""
filename, file_extension = os.path.splitext('/path/to/somefile.ext')
return not file_extension
For the rest of your question just have a look at tutorials like this.

Categories

Resources