open a file which name is contained in a variable - python

I have a hundred of files in a folder which have the form i.ext where I is an integer (0 <= i). I wrote a script which take 2 files in entries but I wanted to use the script with all the files of my folder.
Could I write a script in Python with a loop such a way that the name file is in a variable like this:
from difference import *
# I have a module called "difference"
for i in range (0,100):
for j in range (0,100):
leven(i+".ext",j+".ext") #script in module which take two files in entries
Obviously my code is wrong, but I don't know how can I do :(

You cannot add a number and a string in Python.
'%d.ext' % (i,)

but i wanted to use the script with all the files of my folder.Could i write a script in Python with a loop such a way that the name file is in a variable like this:
This is most certainly possible, but if you want to use all the files from a directory following a certain pattern, I suggest you glob them.
import glob
import difference
ifile_list = glob('*.iext')
jfile_list = glob('*.jext')
for i,j in [[(ifile, jfile) for jfile in jfile_list] for ifile in ifile_list]:
difference.leven(i,j)
However I strongly suggest that instead of hardcodig those file patterns I'd supply them through command line parameters.

use str(i) and str(j) to convert i and j from integer to str.

Related

How to make subfolders inside a parameterized folder?

I made a folder and inside there are 100 subfolders which are made by parameters. Now I want to create one subfolder inside each of this 100 subfolders. But whatever I am doing it is not working.
I added a simple example.
number=[1,2,3]
for i in range (len(number)):
Name = 'GD_%d'%(number[i])
os.mkdir('C:/Temp/t2_t1_18/'+Name) #till this works fine
subfolder_name='S1_%d'%(number[i])
#This does not work and idea somehow not correct
os.mkdir(os.path.join('C:/Temp/t2_t1_18/Name'+subfolder_name))
Some Notes
It is better not to use string concatenation when concatenating paths.
Since you just need the numbers it is better to iterate over them, instead of using range
You can take a look at python's new way of formatting https://realpython.com/python-f-strings/
Assuming I got your question right and you want to create a subdirectory in the newly created directory, I would do something like that
import os
numbers = [1,2,3]
main_dir = os.path.normpath('C:/Temp/t2_t1_18/')
for number in numbers:
dir_name = f'GD_{number}'
# dir_name = 'GD_{}'.format(number) # python < 3.6
dir_path = os.path.join(main_dir, dir_name)
os.mkdir(dir_path)
subdir_name = f'S1_{number}'
subdir_path = os.path.join(dir_path, subdir_name)
os.mkdir(subdir_path)
There is a better answer to your question already.
In your example this should be an easy solution (if your Python version is sufficient):
from pathlib import Path
numbers = (1, 2, 3, 4)
for n in numbers:
Path(f"C:/Temp/t2_t1_18/GD_{n}/S1_{n}").mkdir(parents=True, exist_ok=True)
I'm not certain I understand what you're trying to do, but here is a version of your code that is cleaned up a bit. It assumes the C:\Temp directory exists, and will create 3 folders in C:\Temp, and 1 subfolder in each of those 3 folders.
import os
numbers = [1,2,3]
base_path = os.path.join('C:/', 'Temp')
for number in numbers:
# create the directory C:\Temp\{name}
os.mkdir(os.path.join(base_path, f'GD_{number}'))
# create the directory C:\Temp\{name}\{subfolder_name}
os.mkdir(os.path.join(base_path, f'GD_{number}', f'S1_{number}'))
Some Notes and Tips:
Indentation is part of the syntax in python, so make sure you indent every line that is in a code block (such as your for loop)
There are many ways to format strings, I like f-strings (a.k.a. string interpolation) which were introduced in python 3.6. If you're using an earlier version of python, either update, or use a different string formatting method. Whatever you choose, be consistent.
It is a good idea to use os.path.join() when working with paths, as you were trying to do. I expanded the use of this method in the code above.
As another answer pointed out, you can simply iterate over your numbers collection instead of using range() and indexing.

How to import "dat" file including only certain strings in python

I am trying to import several "dat" files to python spyder.
dat_file_list_images
Here are dat files listed, and there are two types on the list ended with _1 and _2. I wanna import dat files ended with "_1" only.
Is there any way to import them at once with one single loop?
After I import them, I would like to aggregate all to one single matrix.
import os
files_to_import = [f for f in os.listdir(folder_path)
if f.endswith("1")]
Make sure that you know whether the files have a .dat-extension or not - in Windows Explorer, the default setting is to hide file endings, and this will make your code fail if the files have a different ending.
What this code does is called list comprehension - os.listdir() provides all the files in the folder, and you create a list with only the ones that end with "1".
Uses str.endswith() it will return true if the entered string is ended with checking string
According to this website
Syntax: str.endswith(suffix[, start[, end]])
For your case:
You will need a loop to get filenames as String and check it while looping if it ends with "_1"
yourFilename = "yourfilename_1"
if yourFilename.endswith("_1"):
# do your job here

Re-Naming Files as they are being opened in Python For Loop

I'm trying to create a program that will read in multiple .txt files and rename them in one go. I'm able to read them in, but I'm falling flat when it comes to defining them all.
First I tried including an 'as' statement after the open call in my loop, but the files kept overwriting each other since it's only one name I'm defining. I was thinking I could read them in as 'file1', 'file2', 'file3'... etc
Any idea on how I can get this naming step to work in a for loop?
import os
os.chdir("\\My Directory")
#User Inputs:
num_files = 3
#Here, users' actual file names in their directory would be 'A.txt',
'B.txt', 'C.txt'
filenames = [A, B, C]
j = 1
for i in filenames:
while j in range(1,num_files):
open(i + ".txt", 'r').read().split() as file[j]
j =+ 1
I was hoping that each time it read in the file, it would define each one as file#. Clearly, my syntax is wrong because of the way I'm indexing 'file'. I've tried using another for loop in the for loop, but that gave me a syntax error as well. I'm really new to python and programming logic in general. Any help would be much appreciated.
Thank you!
You should probably use the rename() function in the os module. An example could be:
import os
os.rename("stackoverflow.html", "xyz.html")
stack overflow.html would be the name you want to call the file and xyz.html would be the current name of the file/the destination of the file. Hope this helps!

Delete every 1 of 2 or 3 files on a folder with Python

What I'm trying to do is to write a code that will delete a single one of 2 [or 3] files on a folder. I have batch renamed that the file names are incrementing like 0.jpg, 1.jpg, 2.jpg... n.jpg and so on. What I had in mind for the every single of two files scenario was to use something like "if %2 == 0" but couldn't figure out how actually to remove the files from the list object and my folder obviously.
Below is the piece of NON-WORKING code. I guess, it is not working as the file_name is a str.
import os
os.chdir('path_to_my_folder')
for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
print(file_name)
if file_name%2 == 0:
os.remove();
Yes, that's your problem: you're trying to use an integer function on a string. SImply convert:
if int(file_name)%2 == 0:
... that should fix your current problem.
Your filename is a string, like '0.jpg', and you can’t % 2 a string.1
What you want to do is pull the number out of the filename, like this:
name, ext = os.path.splitext(filename)
number = int(name)
And now, you can use number % 2.
(Of course this only works if every file in the directory is named in the format N.jpg, where N is an integer; otherwise you’ll get a ValueError.)
1. Actually, you can do that, it just doesn’t do what you want. For strings, % means printf-style formatting, so filename % 2 means “find the %d or similar format spec in filename and replace it with a string version of 2.
Thanks a lot for the answers! I have amended the code and now it looks like this;
import os
os.chdir('path_to_the_folder')
for f in os.listdir():
name, ext = os.path.splitext(f)
number = int(name)
if number % 2 == 0:
os.remove()
It doesn't give an error but it also doesn't remove/delete the files from the folder. What in the end I want to achieve is that every file name which is divisible by two will be removed so only 1.jpg, 3.jpg, 5.jpg and so on will remain.
Thanks so much for your time.
A non-Python method but sharing for future references;
cd path_to_your_folder
mkdir odd; mv *[13579].png odd
also works os OSX. This reverses the file order but that can be re-corrected easily. Still want to manage this within Python though!

directory and file related doubts?

i have a directory with around 1000 files....i want to run a same code for each of these file...
my code requires the file name to be inputted.
i have written code to copy the information of one into other in other format...
please suggest a method to copy all 1000 files one by one without need to change the file name every time
and i have a field serial_num which need to be continous i.e if 1st file has upto 30 then while coping other file it should continue from 30not from 0 again
require help
thanks..
from string import Template
from string import Formatter
import pickle
f=open("C:/begpython/wavnk/text0004.lab",'r')
p='C:/begpython/wavnk/text0004.wav'
f1=open("C:/begpython/text.txt",'a')
m=[]
i=0
k=f.readline()
while k is not '':
k=f.readline()
k=k.rstrip('\n')
mi=k.split(' ')
m=m+[mi]
i=i+1
y=0
x=[]
j=1
t=(i-2)
while j<t:
k=j-1
l=j+1
if j==120 or j==i:
j=j+1
else:
x=[]
x = x + [y, m[j][2], m[k][2], m[l][2], m[j][0], m[l][0], p]
y=y+1
#f1.writelines(str(x)+'\n')
for item in x:
f1.write(str(item)+' ')
f1.write(str('\n'))
j=j+1
f.close()
f1.close()
my code.....
and i have files name in series like text0001.....text1500.lab and want to run them at a time without need to call them everytime by changin name
enter code here
Why not just use an iterator over the list of files in the directory? I would post some example code but I do get the feeling that you're getting everyone else here to do your whole job for you.
You could take a look at the glob module as well. It's this easy:
import glob
list_of_files = glob.glob('C:/begpython/wavnk/*.lab')
And yes, it works on windows as well.
However, it only finds the matching files, doesn't read them or anything.
By the looks of your code example, you may or may not be interested in the python
csv module as well.
You can list the contents of the directory with [listdir][1].
You can the filter on extension with something like
allnames = listdir...
inputnames = [name for name in allnames \
where os.path.[splitext][2](name)\[1\] == ".lab" ]
You can also look at the filter() or map() built-in functions.
http://docs.python.org/library/os.path.html#os.path.splitext

Categories

Resources