Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to write in a file which changes the name with the counter.
for j in range(30):
fileout.write("bla bla")
and fileout should be
file001 if j=1
file002 if j=2
...
...
I cannot format it in the right way.
Anyone can help me?
Thank you
You can try to use the .zfill( < number of digits > ) option. It will complet your string with 0.
For example, this code should work :
radical ='file'
numberOfDigits = 3
for j in range( 30 ) :
fileout = open ( radical + '%s' %(str(j).zfill(numberOfDigits)) + '.txt' , 'w' )
fileout.write('bla bla')
fileout.close()
Not sure if below means what you needed ?
Code below will create file000 - file029 with 'bla bla' inside
for i in range(30):
with open("file%03d" % i, 'w') as f:
f.write('bla bla')
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Is there any magic python way to get the firsts letters of each name and join with '#company.com' to create a email address?
Here is how I did:
name = ['Elon Reeve Musk']
full_name = [word[0].lower() for word in name[0].split(' ')]
firts_letters = "".join(full_name)
username = '%s#company.com' %(firts_letters)
The result is erm#company.com
Here's some "python magic"
name = ['Elon Reeve Musk']
f"{''.join(filter(str.isupper, name[0]))}#company.com".lower()
>>> erm#company.com
Whether this is better than your method is debatable. Most of the time a few lines of easy to read code is better than a one line hack.
My recommendation would be
name = ['Elon Reeve Musk']
initials = ''.join(word[0] for word in name[0].split())
f'{initials.lower()}#company.com'
>>> erm#company.com
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
[data.txt]
CODE\tUSERNAME\tSPENT\tCOLUM1\tCOLUM2
I want to sort the file [data.txt], using "SPENT". How can i do this?
Yes, of course it is possible. For example:
# read file into array of lines
lines = open("data.txt").readlines()
# sort those lines using a lambda
lines.sort(key = lambda line : line.split("\t")[2])
The lambda extrudes the SPENT column from the row to be used as sorting-key.
def subMenu_5():
# read file into array of lines
lines = open("database").readlines()
# sort those lines using a lambda
lines.sort(key = lambda line : line.split("\t")[3])
clientList = []
dataQuantify = 0
database = open('database','r')
i = 1
while (i == 1):
if (database.readline() == ''):
i = 0
else:
dataQuantify = dataQuantify + 1
database.close()
sortList = open("sortList","w")
for i in range (3):
sortList.write(lines[i])
sortList.close()
print "[Código] [Nome] [Quant. Prod. Comprados] [Valor Gasto] [Descontos] \n"
sortList = open('sortList','r')
i = 0
while (i < dataQuantify):
clientList.append(sortList.readline())
print clientList[i]
i = i + 1
database.close()
raw_input("Precione 'ENTER' para voltar ao menu principal... ")
return
This work! Very Thx!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Could someone help me with following function:
def nagios_chart():
alpha = [chr(item).upper() for item in range(ord('b'), ord('l')+1)]
for idx, column in enumerate(alpha):
print worksheet.write_column('column + 1', nagios_data[idx])
if __name__ == '__main__':
nagios_chart()
I need output like this:
worksheet.write_column('B1', nagios_data[0])
worksheet.write_column('C1', nagios_data[1])
worksheet.write_column('D1', nagios_data[2])
worksheet.write_column('E1', nagios_data[3])
worksheet.write_column('F1', nagios_data[4])
worksheet.write_column('G1', nagios_data[5])
worksheet.write_column('H1', nagios_data[6])
worksheet.write_column('I1', nagios_data[7])
worksheet.write_column('J1', nagios_data[8])
worksheet.write_column('K1', nagios_data[9])
worksheet.write_column('L1', nagios_data[10])
To use the column as a variable, remove it from the quotes so it isn't treated as a string literal. Then you can concatenate it with '1'.
def nagios_chart():
alpha = [chr(item).upper() for item in range(ord('b'), ord('l')+1)]
for idx, column in enumerate(alpha):
print worksheet.write_column(column + '1', nagios_data[idx])
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I defined a function that generates some names and I run from loop:
output = open('/tmp/NameGen-output.txt', 'w')
while True:
var = NameGen(name)
.
.
.
if sth:
output.write(var)
elif other:
output.write(var)
break
else:
break
output.close()
update:
first iteration ,content of NameGen-output.txt:
a
b
c
second iteration:
a
b
c
d
e
and etc
So if I overwrite it the second iteration would be just:
d
e
What I am going to ask is:
As you see var equals NameGen() and for each iteration content of var is written to NameGen-output.txt but I want to overwrite output of for each iteration of NameGen() to NameGen-output.txt no appending to it.
Could you possibly help me?
Thank you
You can truncate the existing file without opening and closing it, and flush to ensure that it is written to:
output = open('/tmp/NameGen-output.txt', 'w')
while True:
var = NameGen()
.
.
.
if not sth and not other:
break
else:
output.flush()
output.seek(0)
output.truncate()
output.write(var)
output.flush()
output.write(var)
if other:
break
output.close()
You could move the file opening (note: using with context manager is preferred) inside the loop:
while True:
var = NameGen()
...
with open('/tmp/NameGen-output.txt', 'w') as output:
output.write(var)
...
...
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to adhere to PEP 8, with a 78 character limit on the length of my lines.
I have the following statement:
startTime = time.strptime(request.GET.get('st', (dt.datetime.now() - dt.timedelta(days=1)).strftime("%d/%b/%Y:%H:%M:%S")), "%d/%b/%Y:%H:%M:%S")
How should I format it so that it adheres to PEP8 (where should I break it into new lines?)
Avoid writing such overly convoluted code in the first place:
if 'st' in request.GET:
startTime = time.strptime(request.GET['st'], "%d/%b/%Y:%H:%M:%S")
else:
startTime = (dt.datetime.now() - dt.timedelta(days=1)).timetuple()
Why generate a default to be parsed out to a timetuple again instead of just going there straight?
startTime = time.strptime(
request.GET.get(
'st',
(
dt.datetime.now() - dt.timedelta(days=1)
).strftime("%d/%b/%Y:%H:%M:%S")
),
"%d/%b/%Y:%H:%M:%S"
)
This one solution, but you use more variables for this. For example:
time_format = "%d/%b/%Y:%H:%M:%S"
yesterday_date = dt.datetime.now() - dt.timedelta(days=1
This would make the code more readable
Split it up into different variables:
a_date = (dt.datetime.now() - dt.timedelta(days=1)).strftime("%d/%b/%Y:%H:%M:%S")
req = request.GET.get('st', a_date)
startTime = time.strptime(req, "%d/%b/%Y:%H:%M:%S")