I used the following line to rename my file by adding timing and remove extra space and replace it with (-)
if i would like to add extra information like lable before the timing ,
filename = ("%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()))).replace(" ", "-")
the current output looks like
testfile_2016-07-25_12:17:14.mp4
im looking to have the file output as
testfile_2016-07-25_12:17:14-MediaFile.mp4
try the following ,
filename = ("%s_%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S","Mediafile",time.localtime()))).replace(" ", "-")
what did i missed here ?
You're using the function strftime incorrectly. Strftime only takes 2 arguments and you're passing it 3.
You would need to generate the string from the time and apply some string operations to append the extra info.
If you want to add MediaFile to the end of the filename simply do something like this.
filename = ("%s_%s-MediaFile.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()))).replace(" ", "-")
filename = ("%s_%s-%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()), 'MediaFile')).replace(' ', '-')
# 'testfile_2016-07-25_10:29:28-MediaFile.mp4'
To understand better how this works and slightly improve readability, you can define your time stamp in a separate variable:
timestr = time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime()) # 2016-07-25_10:31:03
filename = ("%s_%s-%s" %(pfile, timestr, 'MediaFile')).replace(' ', '-')
# 'testfile_2016-07-25_10:31:03-MediaFile.mp4'
or
filename = ("%s_%s-MediaFile.mp4" %(pfile, timestr)).replace(' ', '-')
For completeness, you can also use the format() method:
filename = '{0}_{1}-MediaFile.mp4'.format(pfile, timestr).replace(' ', '-')
What you are looking for should be :
filename = ("%s_%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()),"Mediafile")).replace(" ", "-")
In your original code, the 'Mediafile' string was not in the right place : you put it as an argument of strftime(), when you should put it as one of the string to replace, in the 2nd level of parentheses.
Related
With this python's code I may read all tickers in the tickers.txt file:
fh = open("tickers.txt")
tickers_list = fh.read()
print(tickers_list)
The output that I obtain is this:
A2A.MI, AMP.MI, ATL.MI, AZM.MI, BGN.MI, BMED.MI, BAMI.MI,
Neverthless, I'd like to obtain as ouput a ticker string exactly formatted in this manner:
["A2A.MI", "AMP.MI", "ATL.MI", "AZM.MI", ...]
Any idea?
Thanks in advance.
If you want the output to look in that format you want, you would need to do the following:
tickers_list= "A2A.MI, AMP.MI, ATL.MI, AZM.MI, BGN.MI, BMED.MI, BAMI.MI"
print("["+"".join(['"' + s + '",' for s in tickers_list.split(",")])[:-1]+"]")
With the output:
["A2A.MI"," AMP.MI"," ATL.MI"," AZM.MI"," BGN.MI"," BMED.MI"," BAMI.MI"]
Code explanation:
['"' + s + '",' for s in tickers_list.split(",")]
Creates a list of strings that contain each individual value, with the brackets as well as the comma.
"".join(...)[:-1]
Joins the list of strings into one string, removing the last character which is the extra comma
"["+..+"]"
adds the closing brackets
Another alternative is to simple use:
print(tickers_list.split(","))
However, the output will be slightly different as in:
['A2A.MI', ' AMP.MI', ' ATL.MI', ' AZM.MI', ' BGN.MI', ' BMED.MI', ' BAMI.MI']
Having ' instead of "
A solution for that however is this:
z = str(tickers_list.split(","))
z = z.replace("'",'"')
print(z)
Having the correct output, by replacing that character
you can to use Split function:
tickers_list = fh.read().split(',')
Idk if I'm overthinking this or just really tired, but I was trying to figure out the best way to add text to this function
print(os.path.getsize(os.path.join('/Users/raelynsade/Documents/cpt180stuff/pets/dogs', 'dogs.jpg')), 'bytes')
this is the results
59520 bytes
but I need
dogs.jpg: 5920 bytes
First, get the size in bytes aond convert it to a string:
path_name = '/Users/raelynsade/Documents/cpt180stuff/pets/dogs'
file_name = 'dogs.jpg'
size_string = str(os.path.getsize(os.path.join(path_name, file_name)))
Then concatenate it with the desired text:
output_text = file_name + ': ' + size_string + ' bytes'
print(output_text)
Alternatively, you could use an f-string instead, with the same result:
output_text = f"{file_name}: {size_string} bytes"
print(output_text)
You could do everything on one or two lines like the other answers, but it's always better to be clearer rather than compact, there's no need to sacrifice readability to make code as small as possible:
file_name = "dogs.jpg"
print(f"{file_name}: {str(os.path.getsize(os.path.join('/Users/raelynsade/Documents/cpt180stuff/pets/dogs', file_name)))} bytes")
Maybe I am being dumb but can you do this:
print('dogs jpg:', os.path.getsize(os.path.join('/Users/raelynsade/Documents/cpt180stuff/pets/dogs', 'dogs.jpg')), 'bytes')
Relatively new with python and pandas, hence need some inputs here. Appreciate some response here.
I'm having multiple files with a filename having a combination of text, number and date. I want to have camel casing with an underscore and trimming of white space to a standard format, for eg,
FileName- ARA Inoc Start Times V34 20200418.xlsx to be named as Ara_Inoc_Start_Time_V34_20200418.xlsx
FileName- Batch Start Time V3 20200418.xlsx to be named as Batch_Start_Time_V3_20200418.xlsx
The challenge I'm facing is
1) how to add an underscore before date?
2) with a word in a filename like ARA Inoc Start - my code converts it to A_R_A _Inoc _Start. How to adapt it to Ara_Inoc? this would involve trimming the white space as well. How to add it in current code.
def change_case(str):
res = [str[0].upper()]
for c in str[1:]:
if c in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
res.append('_')
res.append(c.upper())
else:
res.append(c)
return ''.join(res)
# Driver code
for filename in os.listdir("C:\\Users\\t\\Documents\\DummyData\\"):
str = filename
print(change_case(str))
Split the strings using str.split(), convert the first letter using str.upper(), then join them using str.join()
import os
for filename in [
' ARA Inoc Start Times V34 20200418.xlsx ',
' Batch_Start_Time_V3_20200418.xlsx '
]: # os.listdir('C:\\Users\\t\\Documents\\DummyData\\')
new_filename = '_'.join([i[:1].upper()+i[1:].lower() for i in filename.strip().split()])
print(new_filename)
Output:
Ara_Inoc_Start_Times_V34_20200418.xlsx
Batch_start_time_v3_20200418.xlsx
Note the use of i[:1].upper()+i[1:] instead of str.title(). You can use the latter, but that will convert the file extension to title case as well, hence why I used the above instead. Alternatively, you can split the filename and the extension before doing the conversion:
import os
for filename in[
' ARA Inoc Start Times V34 20200418.xlsx ',
' Batch_Start_Time_V3_20200418.xlsx '
]:
filename, ext = filename.rsplit('.', 1)
filename = '_'.join([i.title() for i in filename.strip().lower().split()])
new_filename = '.'.join([filename, ext])
print(new_filename)
Output:
Ara_Inoc_Start_Times_V34_20200418.xlsx
Batch_Start_Time_V3_20200418.xlsx
I'm trying to filter some log files that are in the format of a table/dataset but .endswith() and .startswith() are not meeting my requirments. I'm using an anonymous function but need to adapt my Python code to check if a string contains .jpg
logfilejpg = sc.textFile("/loudacre/logs/*.log").filter(lambda line: line.endswith('.jpg'))
Use in:
'.jpg' in 'something.jpg foo'
Out: True
You can also put it in your lambda expression:
lambda line: '.jpg' in line
Example:
list(filter(lambda line: '.jpg' in line, ["foo", "foo.jpg.bar", "bar.jpg"]))
Out: ['foo.jpg.bar', 'bar.jpg']
To get the index of where the ".jpg" starts at:
hello = "world.jpg"
print(hello.find(".jpg"))
You can split the inintial string by " " (space) then by "." and take the second value in the resulting array. Of course it depends on how your initial string is. The basic idea is you can isolate the ".jpg" and use equal to check.
To verify that the file is actually a jog, you can try to open it. If it fails, the file is ether other format or corrupt, see also the excepption you get.
Using str.find() and len(), you could find the substring like so:
a_string = 'there is a .jpg here.'
start = a_string.find('.jpg') # The lowest index in a_string where '.jpg' is found
end = start + len('.jpg')
print(a_string[start:end])
# .jpg
i have below code in which filenames are FR1.1.csv, FR2.0.csv etc. I am using these names to print in header row but i want to modify these name to FR1.1 , Fr2.0 and so on. Hence i am using strip function to remove .csv. when i have tried it at command prompt its working fine. But when i have added it to main script its not giving output.
for fname in filenames:
print "fname : ", fname
fname.strip('.csv');
print "after strip fname: ", fname
headerline.append(fname+' Compile');
headerline.append(fname+' Run');
output i am getting
fname :FR1.1.csv
after strip fname: FR1.1.csv
required output-->
fname :FR1.1.csv
after strip fname: FR1.1
i guess some indentation problem is there in my code after for loop.
plesae tell me what is the correct way to achive this.
Strings are immutable, so string methods can't change the original string, they return a new one which you need to assign again:
fname = fname.strip('.csv') # no semicolons in Python!
But this call doesn't do what you probably expect it to. It will remove all the leading and trailing characters c, s, v and . from your string:
>>> "cross.csv".strip(".csv")
'ro'
So you probably want to do
import re
fname = re.sub(r"\.csv$", "", fname)
Strings are immutable. strip() returns a new string.
>>> "FR1.1.csv".strip('.csv')
'FR1.1'
>>> m = "FR1.1.csv".strip('.csv')
>>> print(m)
FR1.1
You need to do fname = fname.strip('.csv').
And get rid of the semicolons in the end!
P.S - Please see Jon Clement's comment and Tim Pietzcker's answer to know why this code should not be used.
You probably should use os.path for path manipulations:
import os
#...
for fname in filenames:
print "fname : ", fname
fname = os.path.splitext(fname)[0]
#...
The particular reason why your code fails is provided in other answers.
change
fname.strip('.csv')
with
fname = fname.strip('.csv')