So I have to take the numbers from a certain file
containing:
1 5
2 300
3 3
9 155
7 73
7 0
Multiply them and add them to a new file
I used the script under here but for some reason, it now gives a syntax error.
f=open('multiply.txt')
f2=open('resulted.txt','w')
while True:
line=f.readline()
if len(line)==0:
break
line=line.strip()
result=line.split(" ")
multiply=int(result[0])*int(result[1])
multiply=str(multiply)
answer=print(result[0],"*",result[1],"=",multiply)
f2.write(str(multiply))
f.close()
f2.close()
i found out that f2.write(multiply) works
but i get all the answers as 1 string (5600913955110)
how do i get it to be 1 good text file and give the right calculation
Update:
f=open('multiply.txt')
f2=open('result.txt','w')
while True:
line=f.readline()
if len(line)==0:
break
line=line.strip()
result=line.split(" ")
multiply=int(result[0])*int(result[1])
multiply=str(multiply)
answer=print(result[0],"*",result[1],"=",multiply)
answer=str(answer)
f2.write(str(answer))
f2.write(str(multiply))
f.close()
f2.close()
output:
None5None600None9None1395None511None0
at the end of the code you have this line:
f2.write(str(answer)
notice there is not a ) at the end and you have two ( in the line.
try this:
f2.write(str(answer))
Also the name of the post sounds like its provoking opinion response. Try to change it so it doesn't mention your friend but the problem at hand.
In most programming languages, there are escape sequences. Escape sequences allow you to do many things. in your case you need to add the escape sequence
"\n"
this will add a new line onto each thing you append to the file.
like this:
answer=str(result[0])+"*"+str(result[1])+"="+str(multiply)
print(answer)
f2.write(str(answer)+"\n")
Related
so i do not want the results under each other. How can i line it up next to each other? Like 1 1 1 and not 1 under 1 under 1. I did not find any good information about that. I tried print(x,t) but it do not work for for loops or does it?
here
By default, print() appends a newline character to the end of the string.
To have it not do this, simply use the following:
print("Hello World!", end = "")
I'm working through a few coding problems on this website I found. To my understanding, what the website does to check whether my program is outputting the expected results is that it makes me write the output on a new file line by line, and then it compares my file with the file that contains the answers. I'm trying to submit my solution for a problem and keep getting the following error message:
> Run 1: Execution error: Your program did not produce an answer
that was judged as correct. The program stopped at 0.025 seconds;
it used 9360 KB of memory. At character number 7, your answer says
'<Newline>' while the correct answer says ' '.
Here are the respective outputs:
----- our output ---------
mitnik_2923
Poulsen_557
Tanner_128
Stallman_-311
Ritchie_-1777
Baran_245
Spafford_-1997
Farmer_440
Venema_391
Linus_-599
---- your output ---------
mitnik
_2923Poulsen
_557Tanner
_128Stallman
_-311Ritchie
_-1777Baran
_245Spafford
_-1997Farmer
_440Venema
_391Linus
_-599
--------------------------
I'm pretty sure my program outputs the expected results, but in the wrong format. Now, I've never written stuff on files using Python before, and therefore don't know what I'm supposed to change to get my output in the proper format. Can someone help me? Here's my code:
fin = open ('gift1.in', 'r')
fout = open ('gift1.out', 'w')
NP,d=int(fin.readline()),dict()
for _ in range(NP):
d[fin.readline()]=0
for _ in range(NP):
giver=fin.readline()
amt,ppl=list(map(int,fin.readline().split()))
if ppl==0 or amt==0:sub=-amt;give=0
else:sub=amt-(amt%ppl);give=amt//ppl
d[giver]-=sub
for per in range(ppl):
d[fin.readline()]+=give
for i in d: ##I'm doing the outputting in this for loop..
ans=str(i)+' '+str(d[i])
fout.write(ans)
fout.close()
The line returned by find.readline() includes the trailing newline. You should strip that off before using it as the dictionary key. That's why you see a newline after all the names.
fout.write() doesn't add a newline after the string you're writing, you need to add that explicitly. That's why there's no newline between the number and the next name.
with open ('gift1.in', 'r') as fin:
NP = int(fin.readline())
d = {fin.readline().strip(): 0 for _ in range(NP)}
for _ in range(NP):
giver=fin.readline().strip()
amt, ppl= map(int,fin.readline().split())
if ppl==0 or amt==0:
sub=-amt
give=0
else:
sub=amt-(amt%ppl)
give=amt//ppl
d[giver]-=sub
for per in range(ppl):
d[fin.readline().strip()]+=give
with open ('gift1.out', 'w') as fout:
for i in d: ##I'm doing the outputting in this for loop..
ans= i + " " + str(d[i])+'\n'
fout.write(ans)
Other points:
Don't cram multiple assignments onto the same line unnecessarily. And no need to put the if and else all on 1 line.
i is a string, there's no need to use str(i)
Use a context manager when opening files.
I am trying to make a very simple login script to learn about accessing files and lists but I'm a bit stuck.
newaccno = str(1)
with open("C:\\Python\\Test\\userpasstest.txt","r+") as loginfile:
for line in loginfile.readlines():
line = line.strip()
logininfo = line.split(" ")
print(newaccno in logininfo[0])
while newaccno in logininfo[0]: #issue is here, also tried ==
newaccno += 1
print(newaccno)
loginfile.write(newaccno)
My logic is that it will search logininfo[0] for newaccno and if it is true, increase newaccno by 1 and search again until it is false then write to file (so if the file has 1, 2 and 3 already then newaccno will end up as 4).
Edit: This is how the txt file looks, the first number represents newaccno before it gets split.
1 abc qwe
2 123 456
(adapted from comment)
Your while loop needs to be inside your for loop for it to work. If it is outside logininfo[0] will always be the last line's first character
I'm not sure what I'm doing wrong here, spent all day googling and reading python books..
I have the following function:
def extract(inNo, inputFile2, outputFile):
ifile = open(inputFile2, 'r')
ofile = open(outputFile, 'w')
lines = ifile.readlines()
for line in lines:
print(str(len(line)))
if str(len(line)) == str(inNo):
ofile.write(line)
I'm trying to understand len(), I seem to get odd results when using it.
My input file is the following:
1
22
333
4444
55555
666666
7777777
88888888
Now if I use '7' as the inNo variable, the output (i.e., print) I get is:
2
3
4
5
6
7
8
8
and the output file becomes:
666666
I'm sure from checking in python.exe length count start from 1 i.e:
len('123')
would give a result of
3
Is my understanding of len() wrong, or am I coding it wrong?
Essentially, what this function does is; it takes an input, an output and a character length as arguments. These come from a different function and the 2nd function calls this one with arguments.
This function reads lines from the input file.
For every line, it gets the character length and compares it to the input No.
If they are equal it should write that line to the output file. I assume as I have no "else:" it should carry on the iteration.
The print() function allows me to see exactly what it has calculated as the length.
When I try to add '- 1' or '+ 1' to the len() i.e. (len(line) + 1) it causes even more odd things start to happen.
len() also considers the new line character \n, that's why you're getting one more in every line except the last one.
I have the following problem:
I open a file and read it line by line searching for a specific pattern. When I found it, I would like to write the entire line AND THE NEXT TWO LINES into a new file. The problem is that I don't know how to get from the line that I've found to the next 2.
AAA
XXX
XXX
BBB
XXX
XXX
CCC
XXX
XXX
In this example it would be that I find "BBB" and I want to get the next two lines.
What could I do? Thank you very much for your kind help!
Edit: I realized that I have to ask more precisely.
This is the code from my colleague
for k in range(0,len(watcrd)):
if cvt[k]>cvmin:
intwat+=1
sumcv+=cvt[k]
sumtrj+=trj[k]/((i+1)*sep/100)
endline='%5.2f %5.2f' % (cvt[k],trj[k]/((i+1)*sep/100)) # ivan
ftrj.write(watline[k][:55]+endline+'\n')
fall.write(watline[k][:55]+endline+'\n')
For every k in range I would like to write k, k+1, k+2 to the file ftrj.
Which is the best way to do this?
Edit 2: I am sorry, but I realized that I've made a mistake. What you suggested worked, but I realized that I have to include it in a different part of the code.
for line in lines[model[i]:model[i+1]]:
if line.startswith('ATOM'):
resi=line[22:26]
resn=line[17:20]
atn=line[12:16]
crd=[float(line[31:38]),float(line[38:46]),float(line[46:54])]
if (resn in noprot)==False and atn.strip().startswith('CA')==True:
protcrd.append(crd)
if (resn in reswat)==True and (atn.strip() in atwat)==True:
watcrd.append(crd)
watline.append(line)
I would think of something like this:
(...)
if (resn in reswat)==True and (atn.strip() in atwat)==True:
watcrd.append(crd)
watline.append(line)
for i in range(1, 3):
try:
watcrd.append(crd[line + i])
watline.append(line[line + i])
except IndexError:
break
But it doesn't work. How can I indicate the part and the line that I want to append to this list?
Python file objects are iterators, you can always ask for the next lines:
with open(inputfilename) as infh:
for line in infh:
if line.strip() == 'BBB':
# Get next to lines:
print next(infh)
print next(infh)
Here next() function advances the infh iterator to the next line, returning that line.
However, you are not processing a file; you are processing a list instead; you can always access later indices in the list:
ftrj.write(watline[k][:55]+endline+'\n')
fall.write(watline[k][:55]+endline+'\n')
for i in range(1, 3):
try:
ftrj.write(watline[k + i][:55]+endline+'\n')
fall.write(watline[k + i][:55]+endline+'\n')
except IndexError:
# we ran out of lines in watline
break