Concatenate variable and string python script - python

I am trying to write a Python script in Spyder to deal with several files at the same time.
Actual path is something like:
/TestCondition/TestDate-A1.txt
I want to control the TestCondition and TestDate only at the beginning.
FoldPath = TestCondition
FileName = TestDate
I want to do something like:
dfA1 = pd.read_csv(FoldPath&'/'Filename&'A1.txt'
dfA2 = pd.read_csv(FoldPath&'/'Filename&'A2.txt'
....
dfA12 = pd.read_csv(FoldPath&'/'Filename&'A12.txt'
#Code with Pandas and Numpy...
How do I concatenate the variable names FoldPath and FileName with the string "A1 to A12" specifically to call out a csv file ? I can't find the correct syntax.
Thanks,
J-F
Edit Question solved.
With the knowledge of "import os" and also "os.path.join", I can now find a bunch of examples to do what I intended to do. I know that this question has been asked several times, but with my limited knowledge of Python, and programming in general, I could not find the correct key words. Anyway, thanks again for your quick answers.

You can use os.path.join and the + to concatenate
import os
filepath = os.path.join(FoldPath, FileName + '-A1.txt')
dfA1 = pd.read_csv(filepath ...

first..
dfA1 = pd.read_csv("/{}/{}-A1.txt".format(FoldPath, Filename)
but this code not recommanded.
second.. use os.path.join
dfA1 = pd.read_csv(os.path.join(FoldPath, "{}-A1.txt".format(Filename, ))

Related

There are two logs in the path in file_path, and I want to read each of them using python

There are a,b,c,d folders in the D:\Coding\iroiro\ChuckRep folder, and there are also e,f,g,h folders in it. And there are C000 logs and W logs in this e,f,g,h folder, and I want to bring them in individually, but I don't know if the code I designed is wrong or nothing.
file_path = './ChuckRep/*/*/'
file_name, ext = os.path.splitext(file_path)
for path in glob.glob(file_path):
if ext=='.smm_logs':
cfile_path = glob.glob(file_name[:-4]+'C000.smm_logs')[0]
wfile_paths = glob.glob(file_name[:-4]+'*W*.smm_logs')
print(cfile_path)
How can I print cfile_path and wfile_path to get the result?
If you expand your file_path glob-like, you get only directories.
You try to split extension from a glob pattern string before expansion, which doesn't make sense.
Instead I suggest you start with using os.walk(), I'd say it's less confusing for beginner.

How to change the name of a mp4 video using python

I just want to know how can I change the name of mp4 video using python. I tried looking on the internet but could not find it. I am a beginner in python
you can use os module to rename as follows...
import os
os.rename('full_file_path_old','new_file_name_path)
So firstly let's take an example to make things clear.
Let's suppose you downloaded a playlist from YouTube which follows the following naming
C++ Tutorial Setting IDE #1.mp4 and so on...
Now when this will be saved in your computer it will be in alphabetical order and will be tough for you to watch them in proper order.
So now we know the problem let's solve it with our code and you can modify it according to your convenience.
import os
os.chdir('D:\YouTube\C++')
for f in os.listdir():
f_name, f_ext = os.path.splitext(f)
f_title, f_num = f_name.split('#')
f_title=f_title.strip()
f_num=f_num.strip()
new_name= '{}. {}{}'.format(f_num, f_title, f_ext)
os.rename(f, new_name)
Now let me explain the code to you line by line:
import os is the module we are including to use os.rename and other functions which can be found here [https://docs.python.org/3/library/os.html][1]
os.chdir is used to change your directory to the one which contains all your video files.
Then we run a for loop to go through each and every file using os.listdir which will simply list all the files in our current directory.
Now we use os.path.splitext(f)it splits our path name from its extension. So now
f_name = 'C++ Tutorial Setting IDE #1' and f_ext = .mp4
Now we will use split on our f_name as show and now what this will do is it will separate strings use # as delimiter. Now f_title = C++ Tutorial Setting IDE and f_num = 1
Now both f_title and f_num may have unwanted spaces which can be removed by using simple strip.
Now we will use some string formatting and save the final name in new_name here i have use three curly braces to format my string to look something like this 1. C++ Tutorial Setting IDE.mp4
So I hope this helps.
PS. For more info you can watch this video https://youtu.be/ve2pmm5JqmI

Renaming files (while counting the number)

I'm currently trying to write a python script to rename a bunch of files. The file is named like this: [Name][Number]-[Number]. To give a specific example: milk-00-00. The next file is milk-00-01, then 02, 03 until X. After that milk-01-00 starts with the same pattern.
What I need to do is to switch 'milk' into a number and replace the '-XX-XX' by '-01', '02', ...
I hope you guys get the idea. The current state of my code is pretty poor, it was hard enough to get it this far though. It looks like this and with this I'm at least able to replace something. I'll also manage to get rid of the 'milk' with the help of google. However, if there is an easier way, I'd really appreciate a push in the right direction!
import os
import sys
path = 'C:/Users/milk/Desktop/asd'
i=00
for filename in os.listdir(path):
if filename.endswith('.tiff'):
newname = filename.replace('00', 'i')
os.rename(filename,newname)
i=i+1
You can use the format function
temp = (' ').join(filename.split('.')[:-1])
os.rename(filename, '10{}-{}.tiff'.format(temp.split('-')[-2],temp.split('-')[-1]))
Since filename has the .tiff extension this program first creates a version of filename without the extension - temp - and then creates new names from that.
os.rename(filename, '1000-%02d.tiff' % i)
i += 1

access a file with not fully known filename in python

I have a huge database of files whose names are like:
XYZ-ABC-K09235D1-20151220-5H1E2H4A.txt
XYZ-ABC-W8D2S5G5-20151225-HG2EK4GE.txt
XYZ-ABC-ME2C5K32-20160206-DD8BA4R6.txt
etc...
Names have all the same structure:
'XYZ-ABC-' + 8 random char + '%y%m%d' + 8 random char + '.txt'
Now, I need to open a file, given the date. The point is that, I don't know the exact name of the file, as there are some random chars within. For instance, for datetime 12/05/2014 I know the filename will be something like
XYZ-ABC-????????-20140512-????????.txt
but I don't know the exact name when using f.open command. What could be the best way to do this? (I thought about first creating a list with all filenames, but I don't know whether it's a good technique or if it's better to use something like glob...). Thank you in advance.
You can use following code
import os
fileName = [filename for filename in os.listdir('.') if filename.startswith("prefix") and 'otherstring' in filename]
Hope this helps !

Python - automaticly zip specific folders/files

I have been getting into Python lately and have come across a problem wich i think i could solve using it.
I have a USB stick with a lot of folders in there, the folders each contain the following:
/HTML5/
/Images/
foldername.html
foldername.ofp
preview.html
profile.xml
Now, i have to create a zip file of each folder, but only containing the Images folder and the profile.xml file. There is 40ish folders in there and there will be more in the future.
Here is the final code:
# Script to zip Foldername/Images/ and Foldername/profile.xml to Foldername.zip
import os
import zipfile
dirname = "D:\\testdir"
for schoen in os.listdir(dirname):
print schoen
myZipFile = zipfile.ZipFile(schoen+".zip", "w" )
for f in os.listdir(os.path.join(dirname, schoen)):
print f
if f == "Profile.xml":
print "Found profile.xml"
myZipFile.write(schoen + "\\" + f, f)
elif f == "Images":
print "Found Images"
myZipFile.write(schoen + "\\" + f, f)
myZipFile.close()
Many thanks,
Grootie
Instead of finding random code and trying to guess what it might mean and what you should change, why not look it up in the documentation?
The parameters to ZipFile.write are:
ZipFile.write(filename, arcname=None, compress_type=None)
So your code copies the file named profile.xml into the archive under the name images\\test.py. Is that really what you want? I doubt it. But I'm not sure what you do want. You need to figure that out, in terms you could explain to an idiot (because computers are idiots). Then the docs—or SO, if you get confused by the docs—can help you translate that explanation into the appropriate code.

Categories

Resources