Open existing file of unknown extension - python

I need to open a file for reading, I know the folder it is in, I know it exists and I know the (unique) name of it but I don't know the extension before hand.
How can I open the file for reading?

Use glob to find it:
import os
import glob
filename = glob.glob(os.path.join(folder, name + '.*'))[0]
Or with a generator:
filename = next(glob.iglob(os.path.join(folder, name + '.*')))

Related

How to alter file type and then save to a new directory?

I have been attempting to change all files in a folder of a certain type to another and then save them to another folder I have created.
In my example the files are being changed from '.dna' files to '.fasta' files. I have successfully completed this via this code:
files = Path(directory).glob('*.dna')
for file in files:
record = snapgene_file_to_seqrecord(file)
fasta = record.format("fasta")
print(fasta)
My issue is now with saving these files to a new folder. My attempt has been to use this:
save_path = Path('/Users/user/Documents...')
for file in files:
with open(file,'w') as a:
record = snapgene_file_to_seqrecord(a)
fasta = record.format("fasta").read()
with open(save_path, file).open('w') as f:
f.write(fasta)
No errors come up but it is definitely not working. I can see that there may be an issue with how I am writing this but I can't currently think of a better way to do it.
Thank you in advance!
Hi, You can use os lib to rename the file with the new extension (type)
import os
my_file = 'my_file.txt'
base = os.path.splitext(my_file)[0]
os.rename(my_file, base + '.bin')
And you can use shutil lib to move the file to a new directory.
import shutil
# absolute path
src_path = r"E:\pynative\reports\sales.txt"
dst_path = r"E:\pynative\account\sales.txt"
shutil.move(src_path, dst_path)
Hope that can be of help.

Finding a file in the same directory as the python script (txt file)

file = open(r"C:\Users\MyUsername\Desktop\PythonCode\configure.txt")
Right now this is what im using. However if people download the program on their computer the file wont link because its a specific path. How would i be able to link the file if its in the same folder as the script.
You can use __file__. Technically not every module has this attribute, but if you're not loading your module from a file, loading a text file from the same folder becomes a moot point anyway.
from os.path import abspath, dirname, join
with open(join(dirname(abspath(__file__)), 'configure.txt')):
...
While this will do what you're asking for, it's not necessarily the best way to store configuration.
Use os module to get your current filepath.
import os
this_dir, this_filename = os.path.split(__file__)
myfile = os.path.join(this_dir, 'configure.txt')
file = open(myfile)
# import the OS library
import os
# create the absolute location with correct OS path separator to file
config_file = os.getcwd() + os.path.sep + "configure.txt"
# Open file
file = open(config_file)
This method will make sure the correct path separators are used.

How do I move file types not a specific file in PyCharm?

I am trying to make a program to organize my downloads folder every time I download something, but if I use this code:
import shutil
shutil.move("/Users/plapl/downloads/.zip", "/Users/plapl/Desktop/Shortcuts/winrar files")
shutil.move("/Users/plapl/downloads/.png", "/Users/plapl/Desktop/Shortcuts/images")
It searches for a file name called .zip and .png, but I want it to search for all files that are that type. Can anyone tell me how to do that?
You want to iterate over the files in the directory. Here is an example from source
import shutil
import os
source = os.listdir("/Users/plapl/downloads/")
destination = "/Users/plapl/Desktop/Shortcuts/winrar files"
for files in source:
if files.endswith(".zip"):
shutil.move(files,destination)
I made something based off of that, but it says unresolved reference 'file'
import shutil
import os
source = os.listdir("/Users/plapl/Downloads/")
destination1 = "/Users/plapl/desktop/Shortcuts/images"
destination2 = "/Users/plapl/Shortcuts/winrar files"
destination3 = "/Users/plapl/torrents"
for files in source:
if file.endswith(".png"):
shutil.move(files, destination1)
if file.endswith(".zip"):
shutil.move(files, destination2)
if file.endswith(".torrent"):
shutil.move(files, destination3)
It is complaining for the variable name file which is not defined.
You should use files since that is your iterating variable name.

Python Renaming Multiple Files in Directory

Beginner question: I am trying to rename all .xlsx files within a directory. I understand how to replace a character in string with another, but how about removing? More specifically, I have multiple files in a directory: 0123_TEST_01, 0456_TEST_02. etc. I am trying to remove the prefix in the file name, which would result in the following: TEST_01, TEST_02.
I am attempting to use os.rename and throw it into a loop, but am unsure if I should use len() and some math to try and return the correct naming convention. The below code is where I currently stand. Please let me know if this does not make sense. Thanks.
import os
import shutil
import glob
src_files = os.listdir('C:/Users/acars/Desktop/b')
for file_name in src_files:
os.rename(fileName, filename.replace())
Just split once on an underscore and use the second element, glob will also find all your xlsx file for you are return the full path:
from os import path, rename
from glob import glob
src_files = glob('C:/Users/acars/Desktop/b/*.xlsx')
pth = 'C:/Users/acars/Desktop/b/'
for file_name in src_files:
rename(file_name, path.join(pth, path.basename(file_name).split("_",1)[1])
If you only have xlsx files and you did not use glob you would need to join the paths:
from os import path, rename
from glob import glob
pth = 'C:/Users/acars/Desktop/b'
src_files = os.listdir(pth)
for file_name in src_files:
new = file_name.split("_", 1)[1]
file_name = path.join(pth, file_name)
rename(file_name, path.join(pth, new))
Just split the file name by underscore, ignore the first part, and join it back again.
>>> file_name = '0123_TEST_01'
>>> '_'.join(file_name.split('_')[1:])
'TEST_01'
Your code will look like this:
for file_name in src_files:
os.rename(file_name, '_'.join(file_name.split('_')[1:]))

Check .dat File whether a file exists using Python

How do I check whether a file exists, using Python, Python there are several methods which can be used to check if a file exists, in a certain directory
My code:
PATH = /abc/python
fname = PATH/UP*.dat
if os.path.isfile(fname)
os.path.exists(file) # you cant use wildcard here
os.path.isfile(file) # to check for is it a file or not
You can try this if you want only files:
import os
import glob
PATH = "/abc/python/UP*.dat"
filter(os.path.isfile, glob.glob(PATH))

Categories

Resources