I was trying to copy an image with the path : userDATA\user1\profile_image, but unfortunaly, I don`t know the file extention, because the user can drop his own image, so that the suffix is sometimes different.
file_path = drop_image_instance.image_path # the path looks like this: C:\user\images\download1.png
copyfile(file_path, "userDATA\\" + username + "\\profile_image")
My question is, how can I find out, which suffix the file has, or how can i detect the ending in file_path?
For example:
def find_suffix(path):
file_ending = path[1]
return file_ending
Thanks for answers!
Related
I'm asking for help in trying to create a loop to make this script go through all files in a local directory. Currently I have this script working with a single HTML file, but would like it so it picks the first file in the directory and just loops until it gets to the last file in the directory.
Another way to help would be adding a line to the string would add a (1), (2), (3), etc. at the end if the names are duplicate.
Can anyone help with renaming thousands of files with a string that is parsed with BeautifulSoup4. Each file contains a name and reference number at the same position/line. Could be same name and reference number, or could be different reference number with same name.
import bs4, shutil, os
src_dir = os.getcwd()
print(src_dir)
dest_dir = os.mkdir('subfolder')
os.listdir()
dest_dir = src_dir+"/subfolder"
src_file = os.path.join(src_dir, 'example_filename_here.html')
shutil.copy(src_file, dest_dir)
exampleFile = open('example_filename_here.html')
exampleSoup = bs4.BeautifulSoup(exampleFile.read(), 'html.parser')
elems = exampleSoup.select('.bodycopy')
type(elems)
elems[2].getText()
dst_file = os.path.join(dest_dir, 'example_filename_here.html')
new_dst_file_name = os.path.join(dest_dir, elems[2].getText()+ '.html')
os.rename(dst_file, new_dst_file_name)
os.chdir(dest_dir)
print(elems[2].getText())
Below is the code I am using to convert a binary data into image and then saving it
img = base64.b64decode(rec.image3)
img_conv = Image.open(io.BytesIO(img))
img_format = img_conv.format
img_conv.save('{}/{}'.format(path, rec.image_name), format(img_format))
There are 4 images with same code and I want to handle the scenario where if all the file names are same in the same location, it should force to save the 4 images even though it has duplicate name.
Any suggestion would be appreciated. Thanks.
Supposing that you want to keep each file under a different name: Append '_' to the original filename as long as a file with such a name exists in your directory.
from pathlib import Path
path_to_save = Path(path, rec.image_name)
while path_to_save.exists():
path_to_save = Path(str(path_to_save) + '_')
img_conv.save(path_to_save, format(img_format))
I'm still relatively new to programming and Python. But I am sure this must be possible but my searches are not turning up what I'm looking for.
In my current directory, I have 6 PDF files that I wish to read in via the loop below.
What I would like to do is open each of the PDF's with a new variable name, as you can see it is imaginatively called pdf[1-6]File.pdf.
I can list the files in the console and pull them via the code when I stick breaks in to stop it executing but I can't for the life of me work out how to create the variable name. I thought something like "pdf" + str(i) + "File" would have worked but I'm missing something.
Code is below - not complete but enough so you get what I'm looking at:
#Open the PDF files in the current directory for
#reading in binary mode
def opensource():
listOfFiles = os.listdir('.')
pattern = "*.pdf"
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
# Works to here perfectly
for i in range(len(entry)):
# print(len(entry))
# Trying to create the variable name with
# an incremental numeral in the file name
"pdf" + i + "File" = open(entry, 'rb')
This bit below is how I'm currently doing it and its a pain in the backside. I'm sure it can be done programmatically
#This is the old way. Monolithic and horrid
#Open the files that have to be merged one by one
pdf1File = open('file1.pdf', 'rb')
pdf2File = open('file2.pdf', 'rb')
pdf3File = open('file3.pdf', 'rb')
pdf4File = open('file4.pdf', 'rb')
pdf5File = open('file5.pdf', 'rb')
pdf6File = open('file6.pdf', 'rb')
All help gratefully received.
Thanks
If you are going to use the file pointer outside this for loop, you can very well use a dictionary to do that..
def opensource():
listOfFiles = os.listdir('.')
pattern = "*.pdf"
file_ptrs = {}
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
# Works to here perfectly
for i in range(len(entry)):
# print(len(entry))
# Trying to create the variable name with
# an incremental numeral in the file name
file_ptrs["pdf" + str(i) + "File"] = open(entry, 'rb')
Caution: Its always advisable to use the open method alongside of a "with" clause in python.. it takes care of closing the file once the file operation goes out of context.
I have a variable that is an input for a process. Its essentially the full path name of a file, but injects a value based on a list to get the correct name:
fipsList = ['06001','06037','06059']
for fip in fipsList:
file = r"T:\CCSI\TECH\FEMA\Datasets\NFHL\NFHL_06122018\NFHL_{}_20180518.gdb".format(fip)"
What I want to do now is make everything between "...NFHL_{}_ and ....gdb" to be a wildcard "*". Simply using file = r"T:\CCSI\TECH\FEMA\Datasets\NFHL\NFHL_06122018\NFHL_{}_*.gdb".format(fip)"
doesn't seem to work. Essentially, this is what that produces:
>>>'T:\\CCSI\\TECH\\FEMA\\Datasets\\NFHL\\NFHL_06122018\\NFHL_06_*.gdb'. Suggestions on how to get it to work?
Maybe some old good concat?
Like:
fipsList = ['06001','06037','06059']
for fip in fipsList:
file = "T:\CCSI\TECH\FEMA\Datasets\NFHL\NFHL_06122018\NFHL_{}_" + fip + ".gdb"
Simply adding '*' into a string this way will not work. The set up of the question is poor (my own fault), but for clarification's sake, here's how I resolved the issue:
fipsList = ['06001','06037','06059']
for fip in fipsList:
path = r"T:\CCSI\TECH\FEMA\Datasets\NFHL\NFHL_06122018"
for root, dirs, filename in os.walk(path):
for dir in dirs:
if('NFHL_' + fip[:2] in dir and '.gdb' in dir):
file = os.path.join(root, dir)
Essentially, I had to walk through the folder and use an if conditional to make sure that the conditions of having both the fip value and the .gdb extension were met.
When I run my code, there are no syntax errors, but it is not appending into the file. Basically, the user inputs their class and name (although this appears at the start of the program) and the program formulates a folder name and a file name - the file name being the user's name. The program then checks in the appropriate folder whether there is an existing file under the same name. If there isn't, the program creates a file in the correct folder and writes the user's score. The next time the same user runs the program, the file should be found. Python does output "File found", but the user's second score is not appended into the file. Any help on how to fix this?
All help is appreciated, thanks
Class_number = (input("Please enter your class: "))
score = (input("Please enter your score: "))
Folder = ("Class" + (Class_number))
File_name = (Name) + ".txt"
path = os.path.join("/Computing/a453/Task 3/",(Folder),(File_name))
if os.path.exists(path):
print("File found")
file = open((File_name), "a")
file.write((score) + "\n")
file.close()
else:
print("File not found. Creating file")
CompleteFile = os.path.join(Folder, File_name)
file = open(CompleteFile, "w")
file.write((score) + "\n")
file.close()
Short answer
You are checking if the file is present in a subfolder. If it is not present you create a new file in the desired folder and add the first score. If the file is present you are opening a different file! In the second case, the call to open just uses the filename without the folder (open(File_name, "a")) and not the whole path (open(CompleteFile, "w")).
Further Reading
Is there a special reason why you have to decide whether or not the file exists? Using open with mode a will create the file if it does not exist and append to it if it exists.
Note: open will not create missing folders for you!
Additionally, I would recommend to use Python's with statement (see this tutorial), as it will take care the file gets closed even if an exception is raised.
Combining everything said above your program would end up like this:
import os
name = "Test" # I had to come up with something
class_number = input("Please enter your class: ")
score = input("Please enter your score: ")
folder = "Class" + class_number
file_name = name + ".txt"
path = os.path.join(folder, file_name)
if os.path.exists(path):
print("File found")
else:
print("File not found. Creating file")
with open(path, "a") as txt_file:
txt_file.write(score + "\n")
In general, please check back with your Python reference. As someone told you in a comment, there are a lot of unnecessary parentheses and the style in naming your variables is not really consistent (have a look at Python's "official/recommended" naming conventions).
There are good online resources showing you the basics of Python. I personally enjoyed learning through Codecademy a lot (it's absolutely free).