Not all of arguments converted during string formatting - python

Im wrtiting a script which saves the current date and time as a filename but I get an error stating "TypeError: not all arguments converted during string formatting" I am new to Python andmay of missed something obvious. Code below:
from subprocess import Popen
import datetime
today = datetime.date.today()
today = str(today)
print today
f = open("%s.sql", "w" % (today))
x = Popen(["mysqldump", "-u", "root", "-pucsdrv", "normalisationtion"], stdout = f)
x.wait()
f.close()

You're putting the string formatting in the wrong place; it needs to be right after the string that's being formatted:
f = open("%s.sql" % (today), "w")
It's legal to not pass any formatting arguments, like you did with "%s.sql", but it's not legal to pass arguments but not the right amount ("w" % (today) passes one, but there's no string formatting in "w", so you get an error that not all of the arguments were used)

f = open("%s.sql" % today, "w")

Related

TypeError: list indices must be integers or slices, not str error

I'm making a python that changes lines through arguments, but it's giving an error:
TypeError: list indices must be integers or slices, not str
Script:
import os
import sys
from pathlib import Path
pathh = os.path.basename(__file__)
pathhh = pathh.replace("py", "exe")
path_to_file = f'{sys.argv[1]}'
path = Path(path_to_file)
if path.is_file():
if len(sys.argv) > 1:
def replace_line(file_name, line_num, text):
lines = open(file_name, 'r').readlines()
lines[line_num] = text
out = open(file_name, 'w')
out.writelines(lines)
out.close()
my_list = [f'{sys.argv[1]}', f'{sys.argv[2]}', f'{sys.argv[3]}']
my_str = '0'
my_str2 = '1'
my_str3 = '2'
result = my_list[int(my_str)]
result1 = my_list[int(my_str2)]
result2 = my_list[int(my_str3)]
replace_line(f'{result}', f'{result1}', f'{result2}')
else:
print(f"Usage: {pathh} <File> <LINE> <TOEDIT>")
print("This program was made by CookieYT#9267")
else:
print(f"Usage: {pathh} <File> <LINE> <TOEDIT>")
print("This program was made by CookieYT#9267")
I've tried several ways, and nothing
Does anyone know how to solve it?
The line_num argument to replace_line() is supposed to be an integer, so you can use it in lines[line_num]. So don't format it as a string when you call the function.
There's no need to put the other arguments in f-strings, either, since they're already strings.
replace_line(result, result1, result2)
Similarly, all the elements of sys.argv are strings, you don't need to put them in f-strings, either. So you should write
my_list = sys.argv[1:4]
And if you just want to convert a variable to a string, use str(variable) rather than f'{variable}'. They're equivalent, but str() is the more common idiom. F-strings should be used when you need to add more formatting text, combine multiple variables, or need to specify formatting options (e.g. field size, justification, number of decimal places, etc.).

Error: time data "b'YYYY/MM/DD" does not match format '%Y/%m/%d' but it does

I'm trying to parse dates from a textfile, but executing the scripts throws incorrect data format, when the format is correct.
The file is a .txt file with the following structure
2018/02/15 05:00:13 - somestring - anotherstring
2018/02/15 05:00:14 - somestring - anotherstring
2018/02/15 05:00:15 - somestring - anotherstring
... etc
The script gets the file divided in lines, and each line is divided on fields, of which one field is a date and time. I divided the date and the time in two separate fields, the time gets converted ok so the problem is in the date.
This is what I get on execution:
ValueError: time data "b'2018/02/15" does not match format '%Y/%m/%d'
I noticed it prints the string with a "b" in front of it, which if I'm not mistaken it means it's a byte literal. I've tried using "decode("utf-8")" on it, but it throw's exception as "string" has no method decode.
#the file is in one long string as I get it from a 'cat' bash command via ssh
file = str(stdout.read()) #reads the cat into a long string
strings = file.split("\\n") #splits the string into lines
for string in strings:
fields = string.split(" - ")
if len(fields) >= 3:
#dates.append(datetime.strptime(campos[0],"%Y/%m/%d %H:%M:%S")) #Wrong format
datentime = fields[0].split()
dates.append(datetime.strptime(datentime[0],"%Y/%m/%d")) #Wrong format
print(datentime[1])
dates.append(datetime.strptime(datentime[1],"%H:%M:%S")) #WORKS
I can't figure out why that is happening to you with the code you gave so I can't offer a fix for that but I tried testing on it and this worked for me:
datetime.strptime(str(datentime[0])[2,:-1], "%Y/%m/%d")
It removes the B and ' from the string, if you still have problems with that, please post how you got that string, maybe there was some error on the way.
use try and except:
import datetime
def convertDate(d):
strptime = datetime.datetime.strptime
try:
return strptime(d, "%Y/%m/%d")
except TypeError:
return strptime(d.decode("utf-8"), "%Y/%m/%d")
print(convertDate(b'2018/02/15'))
print(convertDate('2018/02/15'))

How to convert a downloaded string to datetime format?

I am trying to check if today's date < date downloaded from text file online. Here is my code :
import datetime
import requests
URL = "http://directlinktotextfile.com/text.txt"
result = requests.get(URL)
today = datetime.datetime.now().date()
Url_date = result.text
Url_date.strip()
Url_date = datetime.date(Url_date)
if today < Url_date :
print "Today is less than future date"
raw_input()
else:
print "Today is greater than or = to future date"
raw_input()
The result that comes back is just this : 2018,02,14. I use .strip() in case there might be blank spaces or extra lines. I've printed out result.text after strip() and it shows the correct details. Why is it that I can't check if today < Url_date. It works fine if I enter manually a date into datetime.date(2018,02,14), but when I'm downloading the string it won't work. Any suggestions?
You pass string to datetime.date() which should be each an integer.
Url_list = []
Url_list = Url_date.split(",")
yr = int(Url_list[0])
mn = int(Url_list[1])
d = int(Url_list[2])
Now pass these integers to datetime.date
Url_date = datetime.date(yr, mn, d)
The arguments you pass to datetime.date(arg1, arg2, arg3) are not strings as a whole. When you pass it from url, what you are actually doing is
datetime.date("2018,2,14")
Note that you are passing only one string argument and not 3 different integers. You should split the date string using comma and then convert each into integers and then pass them as arguments to datetime.date.
Here is what your code is trying to do :
Url_date = datetime.date("2018,02,14")
But he wants to have:
Url_date = datetime.date(2018,02,14)
Do
Url_date.split(',') # Result: ['2018','02','14']
And then convert all the string in the array in integers
It should be ok :)
Use strptime:
import datetime
today = datetime.datetime.now().date()
parsed = datetime.datetime.strptime("2018,02,14", "%Y,%m,%d").date()
print(today < parsed) # True

Python - Add Date Stamp To Text File

In Python v2, is there a way to get a date/time stamp and put it into creating a new text file?
IE: When I want to create a new text file and write the contents of my program to it, it will create a new text file with the time/date in it.
Thanks for any help.
import datetime
def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
return datetime.datetime.now().strftime(fmt).format(fname=fname)
with open(timeStamped('myfile.txt'),'w') as outf:
outf.write('data!')
This will prepend a timestamp to the front of the filename:
from datetime import datetime
# define a timestamp format you like
FORMAT = '%Y%m%d%H%M%S'
path = 'foo.txt'
data = 'data to be written to the file\n'
new_path = '%s_%s' % (datetime.now().strftime(FORMAT), path)
open(new_path, 'w').write(data)
import datetime
f=open("/home/rohitsai/Documents/acs.txt",'a')
f.write ("heloo"+'\t')
f.write(datetime.datetime.now().ctime())
print datetime.datetime.now()
this code will add helo as well as current date on same file. 'a' is for append mode, \t for tab space.
import datetime
open("file", "w").write(datetime.datetime.now().ctime())
open(datetime.datetime.now().ctime(), "w").write("foo")
I like just having the date in my file handles:
from datetime import date
def timeIzNow():
'''
returns current date as a string
'''
now = date.today()
full = "-" + str(now.month) + "-" + str(now.day) + "-" + str(now.year)
return full
fileN = "findGenes"
with open(fileN + timeIzNow() + ".txt", 'w') as f:
#DO STUFF
Your new file name will look like
findGenes-6-5-2013.txt
A lot of these answers are unnecessarily complicated if you just want to spit out a timestamp to a file and don't care about tweaking the format of said stamp
You can literally do it in one line:
f.write(datetime.now().__str__() + "\n")
Here I assume f is a file - so we print the string representation of datetime.now() and add a new line, because write() doesn't do that for you. (You probably already knew that though.)
Note: checked working with Python 3, I didn't test with Python 2, I'm not sure which version of the language spec you are using.

Python Error: TypeError: not all arguments converted during string formatting

First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options but I'd like to keep it consistent and pull from that file:
vshare = str(raw_input('Share the user needs access to: '))
vrights = str(raw_input('Should this user be Read Only? (y/n): '))
f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr'))
#f = open("/etc/vsftpd_user_conf/%s" % (vusername) , 'wr' )
f.write("local_root=%s/%s" % (config['vsftp']['local_root_dir'], vshare))
if vrights.lower() in ['y', 'ye', 'yes']:
buffer = []
for line in f.readlines():
if 'write_enable=' in line:
buffer.append('write_enable=NO')
else:
buffer.append(line)
f.writelines(buffer)
f.close()
The error I'm getting is:
TypeError: not all arguments converted during string formatting
If I uncomment the commented line it works and makes it a bit further and errors out as well..But I'll deal with that once I get this hiccup sorted.
Your tuple is misshaped
f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr'))
Should be
f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername)), 'wr')
The error is here:
open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr'))
You have three parameters, but only two %s in the string. You probably meant to say:
open("%s/%s" % (config['vsftp']['user_dir'], vusername), 'wr')
Although 'wr' is unclear, you probably mean w+ or r+.
http://docs.python.org/library/functions.html#open
f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr'))
You are passing three arguments (config['vsftp']['user_dir'], (vusername), 'wr') to a format string expecting two: "%s/%s". So the error is telling you that there is an argument to the format string that is not being used.
I think you have a wrong parenthesis, your line should be:
f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername)), 'wr')
It looks like this line should be:
f = open("%s/%s" % (config['vsftp']['user_dir'], vusername), 'wr')
(I moved the closing parenthesis over.)

Categories