How do I read specific characters of filename in Python 2.7 - python

Lets say I have a bunch of folders/files with a name like
abc_06082018
where the numbers are the date it was created but they are different for each folder, however the abc_ stays the same for every name.
How do I only read after the abc_ and up until 8 number in?
BTW: The folder is the current working directory of the python 2.7 program, so i'm using os.getcwd() and saving it to a variable most likely as a string. The idea is to get the date from the cwd and make a file in the cwd in the form of
newfile_06082018.txt
where the numbers are taken from the name of the cwd
Thank you!

The name of the folder is in a string - just use normal string manipulation! .partition() is your friend.
folder = os.getcwd()
absolute_folder = os.path.abspath(folder)
only_folder_name = os.path.basename(absolute_folder)
prefix, sep, date_suffix = only_folder_name.partition('_')
filename = 'newfile_{date}.txt'.format(date=date_suffix)

Related

Change the file name by using python

I would like to change the file name in the folder, there are jpg file but corrupted with product id number. I tried to rename it and delete the string after ".jpg" by using python, here is the code, but there is no any change.
Do you guys have any suggestion?
import os
path=input('C:\\Users\\pengoul\\Downloads\\Files\\PIC\\')
def rename(path):
for file in os.listdir(path):
if file.endswith(".jpg#v=*"):
print(file)
newfile=file.split("#",1)[0]
newName=file.replace(file,newfile)
os.rename(os.path.join(path,file),os.path.join(path,newName))
rename(path)
print("End")
Rename the file of one folder and delete the string after .jpg by using python.
if you input path from user, python automatically use "\" instead of "\\" so you shouldn't use "\\" while input. So I suggest one of these two ways:
path = input("Input your Path: ")
# And the user entered this: C:\Users\pengoul\Downloads\Files\PIC
or
path = 'C:\\Users\\pengoul\\Downloads\\Files\\PIC'
or
path = r'C:\Users\pengoul\Downloads\Files\PIC'
I hope that works for you. If not, make us aware of that!

Count the number of files in a directory in a relative path python

I am trying to count the number of files in a directory. This program counts the number of photos of a person. The person's name is used as the file's name.
Here is the full file path
C:\Users\barry\PycharmProjects\face_rec\images\Barry
I have looked at How to count the number of files in a directory using Python and came up with this solution:
numberOfFile=(len([filename for filename in os.listdir('images/'+name.get()) if os.path.isfile('images/'+name.get())]))
print(numberOfFile)
However this solution always returns 0
I would like to avoid using the absolute path, but if the only option is using the absolute path, that is fine.
You aren't making use of the filename variable with which you iterate through the list returned by os.listdir. You can use os.path.join to join the directory name with it so that it can be found by os.path.isfile:
numberOfFile = len([filename for filename in os.listdir('images/' + name.get())
if os.path.isfile(os.path.join('images/' + name.get(), filename))])

How can I modify my script to allow Python to search recursively thought my folder structure?

Hello fellow Pythonistas,
I have a script which searches through all files contained within a single directory for a 'string' keyword. If it finds the 'string' keyword within any of the files, it will print the name of this file to the IDLE command screen. It seems to work quite well. The inputs are gathered by the program using user prompts.Typically I am searching for a single word within a large series of text files.
HOWEVER - Now I want to build on this in two ways
1) I want to modify the code to that it can also search through all the files contained within sub-folders within the specified directory.
2) I would also like to specify that the searches are limited to a certain type of file extension such as .txt.
Can anyone provide some guidance on either of these two enhancements ???
I am using Python 3 and am VERY new to Python (Just started playing with it 2 weeks ago in an attempt to automate some boring searches through my employers folder structures)
Much appreciated to anyone who can provide some help.
Cheers,
Fraz
# This script will search through all files within a single directory for a single key word
# If the script finds the word within any of the files it will print the name of this file to the command line
import os
print ('When answering questions, do not add a space and use forward slash separators on file paths')
print ('')
# Variables to be defined by user input
user_input = input('Paste the directory you want to search?')
directory = os.listdir(user_input)
searchstring = input('What word are you trying to find within these files?')
for fname in directory:
if os.path.isfile(user_input + os.sep + fname):
# Full path
f = open(user_input + os.sep + fname, 'r')
if searchstring in f.read():
print('found string in file "%s"' % fname)
f.close()enter code here

Rename files using python

I want to rename a file from say {file1} to {file2}. I read about os.rename(file1,file2) in python and is able to do so.
I succeeded only when the the file is placed in the same folder as python script, so I want to ask how can we rename files of other folders i.e. different folder than the one in which python script is placed.
Just use the full path, instead of the relative path:
oldFile = 'C:\\folder\\subfolder\\inFile.txt'
newFile = 'C:\\foo\\bar\\somewhere\\other\\outFile.txt'
os.rename(oldFile, newFile)
To get the double-slash behavior, you can do the following
import os
oldFile = r'C:\folder\subfolder\inFile.txt' # note the r character for raw string
os.path.normpath(oldFile)
Output
'C:\\folder\\subfolder\\inFile.txt'
As others have noted, you need to use full path.
On the other note, take a look at shutil.move documentation, it can also be used for renaming.

File or directory doesn't exist

I'm trying to use the current date as the file's name, but it seems either this can't be done or I'm doing something wrong. I used a variable as a name for a file before, but this doesn't seem to work.
This is what I tried:
import time
d = time.strftime("%d/%m/%Y")
with open(d +".txt", "a+") as f:
f.write("")
This is just to see if it create the file. As you can see I tried with a+ because I read that creates the file if it doesn't exist and I still get the same error.
The problem is with how you're using the date:
d = time.strftime("%d/%m/%Y")
You can't have a / in a filename, because that's a directory instead. You haven't made the directory yet. Try using hyphens instead:
d = time.strftime("%d-%m-%Y")
You almost certainly don't want to make directories in the structure day/month/year, so I assume that's not what you were intending.
You are including directory separators (/) in your filename, and those directories are not created for you when you try to open a file. There is either no 26/ directory or no 26/02/ directory in your current working path.
You'll either have to create those directories by other means, or if you didn't mean for the day and month to be directories, change your slashes to a different separator character:
d = time.strftime("%d-%m-%Y")

Categories