output in text file is not the same as python output - python

I came across a problem. Whenever I run the code the output in Python is correct. all numbers show like this.
1
2
3
4
5
When writing the output to a file. all the numbers are stored in a single line like this:
12345
anybody able to help out?
this is the code:
def main():
Numberfile = open ('number_list.txt', 'w')
s = 0
while s < 100:
s += 1
Numberfile.write(str(s))
print (s)
Numberfile.close()
main()

print() adds newlines for you. Writing to a file does not.
Either add the newline explitily:
Numberfile.write(str(s) + '\n')
or use the print() function for writing to the file:
print(s, file=Numberfile)
This all assumes you are using Python 3; in Python 2, you can still replace the print statement with the same print() function on a module-by-module basis by adding:
from __future__ import print_function
at the top of the module.

Related

Python Label Printer Program

I want to print two labels that have the same numbers on them. I am using ZPL. I have already made my print format in ZPL and it works properly. I am trying to print a data range. For example:
"What is the first number in the range?" User inputs 100
"What is the second number in the range?" User inputs 120
I would then get 40 labels in order.
I then want it to export that data into a notepad file and then print it to my default printer. My problem is that to print with ZPL I have to "tag" my data range with my ZPL code. I cant figure out how to get my data range to go into my print statement correctly. Please help. Thank you in advance!
import os
import sys
start = int(input("Enter the start of range: "))
end = int(input("Enter the end of range: "))
with open('TestFile.txt', 'a') as sys.stdout:
print('^XA')
print('^PQ2')
for labelRange in range(start, end + 1):
print('^FO185,50^A0,300^FD')(labelRange, end = " ")('^FS')
#print('\n')
print('^XZ')
os.startfile("C:/Users/joe.smith/desktop/TestFile.txt", "print")
exit()
here is something to get you started, but I doubt it is complete. You will need to provide a valid ZPL file for making the changes.
I also made the program use fixed numbers for now and so it just runs and outputs.You can change it back once you have it working.
start = 110
end = 111
notepad = ''
# these are header lines that go once (if windows you might need \r\n instead of \n)
notepad += '^XA\n'
notepad += '^PQ2\n'
for label in range(start, end + 1):
# use f-strings
notepad += f'^FO185,50^A0,300^FD{label}^FS\n'
# if you need some of those other numbers to increment
# then setup a counter and do the math here inside the f-string
notepad += f'^FO185,50^A0,300^FD{label}^FS\n'
notepad += '^XZ\n'
# with open('tf.txt', 'w') as sys.stdout:
# print(notepad)
print(notepad)
exit()
outputs:
^XA
^PQ2
^FO185,50^A0,300^FD110^FS
^FO185,50^A0,300^FD110^FS
^FO185,50^A0,300^FD111^FS
^FO185,50^A0,300^FD111^FS
^XZ

My program can't write output in a file in the expected format

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.

Is it possible to read spin text from 1 file & write it in another text file without bracket in python3?

I am stuck & i need your help guys. Here is what i want this program to do. I have 1 text file named spin.txt which contains spin text like {something there|Source|something here} baz {why not find out more|these guys} & i have another text file named write.txt now i want to read from spin.txt file & write it to write.txt file. What i have done. Everything is working fine but the only problem i am getting is when writing to write.txt file it adds bracket & ' like this - [' wrote here'] but i don't want this i only want to write that text. I am using python 3x on windows 10.
**My code :-**
import re
import itertools
p = re.compile("(\{[^\}]+\}|[^\{\}]*)")
spin_comments =open("C:\\Users\\Desktop\\spin.txt","r")
file = str(spin_comments.readlines())
frags = p.split(file)
def options(s):
if len(s) > 0 and s[0] == '{':
return [opt for opt in s[1:-1].split('|')]
return [s]
opt_lists = [options(frag) for frag in frags]
write_text = open("C:\\Users\\Desktop\\write.txt","w")
for spec in itertools.product(*opt_lists):
a = ''.join(spec)
write_text.write(a + '\n')
print(a)
write_comment.close()
''.join(spec)[2:-2]
Just changing this in code it works. Thanks for reply #bit

Bell character as Fields separator in Python print output

I am fairly new to Python and need a little help here.
I have a Python script running on Python 2.6 that parses some JSON.
Example Code:
if "prid" in data[p]["prdts"][n]:
print data[p]["products"][n]["prid"],
if "metrics" in data[p]["prdts"][n]:
lenmet = len(data[p]["prdts"][n]["metrics"])
i = 0
while (i < lenmet):
if (data[p]["prdts"][n]["metrics"][i]["metricId"] == "price"):
print data[p]["prdts"][n]["metrics"][i]["metricValue"]["value"]
break
Now, this prints values in 2 columns:
prid price
123 20
234 40
As you see the fields separator above is ' '. How can I put a field separator like BEL character in the output?
Sample expected output:
prid price
123^G20
234^G40
FWIW, your while loop doesn't increment i, so it will loop forever, but I assume that was just a copy & paste error, and I'll ignore it in the rest of my answer.
If you want to use two separate print statements to print your data on one line you can't avoid getting that space produced by the first print statement. Instead, simply save the prid data until you can print it with the price in one go using string concatenation. Eg,
if "prid" in data[p]["prdts"][n]:
prid = [data[p]["products"][n]["prid"]]
if "metrics" in data[p]["prdts"][n]:
lenmet = len(data[p]["prdts"][n]["metrics"])
i = 0
while (i < lenmet):
if (data[p]["prdts"][n]["metrics"][i]["metricId"] == "price"):
price = data[p]["prdts"][n]["metrics"][i]["metricValue"]["value"]
print str(prid) + '\a' + str(price)
break
Note that I'm explicitly converting the prid and price to string. Obviously, if either of those items is already a string then you don't need to wrap it in str(). Normally, we can let print convert objects to string for us, but we can't do
print prid, '\a', price
here because that will give us an unwanted space between each item.
Another approach is to make use of the new print() function, which we can import using a __future__ import at the top of the script, before other imports:
from __future__ import print_function
# ...
if "prid" in data[p]["prdts"][n]:
print(data[p]["products"][n]["prid"], end='\a')
if "metrics" in data[p]["prdts"][n]:
lenmet = len(data[p]["prdts"][n]["metrics"])
i = 0
while (i < lenmet):
if (data[p]["prdts"][n]["metrics"][i]["metricId"] == "price"):
print(data[p]["prdts"][n]["metrics"][i]["metricValue"]["value"])
break
I don't understand why you want to use BEL as a separator rather than something more conventional, eg TAB. The BEL char may print as ^G in your terminal, but it's invisible in mine, and if you save this output to a text file it may not display correctly in a text viewer / editor.
BTW, It would have been better if you posted a Minimal, Complete, Verifiable Example that focuses on your actual printing problem, rather than all that crazy JSON parsing stuff, which just makes your question look more complicated than it really is, and makes it impossible to test your code or their modifications to it.

Piping my Python Program through another program

I'm trying to make program using Python.
I want to be able to pipe program through another program:
" #EXAMPLE " ./my_python | another programme "
Here is the code I have so far.
This code saves output to file:
#!/usr/bin/env python
import os, random, string
# This is not my own code
''' As far asi know, It belongs to NullUserException. Was found on stackoverflow.com'''
length = 8
chars = string.ascii_letters.upper()+string.digits
random.seed = (os.urandom(1024))
# my code
file_out = open('newRa.txt','w') # Create a 'FILE' to save Generated Passwords
list1=[]
while len(list1) < 100000:
list1.append(''.join(random.choice(chars) for i in range(length)))
for item in list1:
file_out.write('%s\n' % item)
file_out.close()
file_out1=open('test.txt','w')
for x in list1:
file_out1.write('%s\n' %x[::-1])
This is the code I have trying to pipe it through another program:
#!/usr/bin/env python
import os,string,random,sys
length = 8
chars = string.ascii_letters.upper()+string.digits
random.seed = (os.urandom(1024))
keep=[]
keep1=[]
while len(keep)<1000:
keep.append(''.join(random.choice(chars) for i in range(length)))
print '\n',keep[::-1]
for x in keep:
keep1.append(x[::-1])
while len(keep1) < 1000:
print keep1
I have tried chmod and using the script as a executable.
Ok sorry for my lack of google search.
sys.stdout is the answer
#!/usr/bin/env python
import os,string,random,sys
length = 8
chars = string.ascii_letters.upper()+string.digits
random.seed = (os.urandom(1024))
keep=[]
while len(keep)<1000:
keep = (''.join(random.choice(chars) for i in range(length)))
print sys.stdout.write(keep)
sys.stdout.flush()
I stripped my code down (as it makes it a lot faster, But I'm getting this when execute
my code........
P5DBLF4KNone
DVFV3JQVNone
CIMKZFP0None
UZ1QA3HTNone
How do I get rid of the 'None' on the end?
What I have done to cause this ?
Should This Be A Seperate Question??

Categories