How do I write a concatenated string to a file? [duplicate] - python

This question already has answers here:
How to redirect 'print' output to a file?
(15 answers)
Closed 2 years ago.
So I have this piece of code here
#inside of a repeating "while loop"
print(even,flush=True, end=inbetween) #inbetween is what's between each number. (space, new line, etc.)
even=even+2
Which prints out a sequence of even numbers in my number generator
(https://github.com/JasonDerulo1259/JasonsGenerator)
The issue I have with it is that When I do f.write to write the result It says that I am not allowed to write something with multiple arguements. What is the work-around for this?
(here's the syntax error that shows)
File "main.py", line 34, in massprint
f.write(even,flush=True, end=inbetween)
TypeError: write() takes no keyword arguments
Also, If i try put even,flush=True, end=inbetween inside of a variable, I get this syntax error no matter how I change it.
File "main.py", line 32
placeholdervar=[even,flush=True, end=inbetween]
^
SyntaxError: invalid syntax

"Just do print(even,flush=True, end=inbetween, file=f)
– Tomerikoo"
And to print to file and console. Just add another without 'file=f'

Related

Can't read a name from a file if it is made of letters [duplicate]

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 4 years ago.
Using VScode + code runner extension
Once input() function receives a string like "qwe", program returns "NameError: name "qwe" is not defined"
If input receives a string of numbers like "123", everything goes well.
All files exist in right directory,and named/formatted pretty fine.
Example of function:
def maker():
fileVar = str(input())
fileVar = lineFixer(fileVar)
with open(fileVar+".csv","r") as workfile:
for line in workfile:
return(line)
lineFixer is a dumb function for some cases (has no influence on result):
def lineFixer(line):
line = line.strip('\n')
line = line.strip('\t')
line = line.replace('\n','')
line = line.replace('\t','')
return line
Without str(input()), it's rubbish.
The trouble that you are having is because you are using input() rather than raw_input().
Modify your code to read fileVar = raw_input()
The difference between these two is that input is trying to evaluate your input as code. That's why you get the error with XYZ not being defined, it thinks it is a variable. Also, with using raw_input, you no longer should need the casting into a string with str().
EDIT: I am assuming, since you have not specified this and from the error you are getting, that you are using Python2.X. In Python3, there should be only input(), working as raw_input().

Python 3: Reading string from file and define the same string in code working differently [duplicate]

This question already has answers here:
Process escape sequences in a string in Python
(8 answers)
Closed 4 years ago.
I have a text file like below
# 1.txt
who is the\u00a0winners\u00a0where\u00a0season result\u00a0is 7th
If I read a file and print it, it shows
>>> s = open("1.txt").read()
>>> print(s)
who is the\u00a0winners\u00a0where\u00a0season result\u00a0is 7th
However, If I do like below with the same string,
>> s = "who is the\u00a0winners\u00a0where\u00a0season result\u00a0is 7th"
>> print(s)
who is the winners where season result is 7th
I want to read a text file like "1.txt" and print it like the below one. I can not find how to do it. Please help me. Thanks.
\u00a0 is a non break space and is one character.
In your first example your are reading \u00a0 as 6 chars.
If you want to read a file with \u00a0s and interpret them as spaces, you would have to parse the file yourself and create spaces for each \u00a0.

Python dictionary SyntaxError

I'm moving to Python from PHP and I seem to be stuck in my first hour of learning Python.
This seems to be such a basic question that I'm having trouble finding an answer - so please forgive me.
When I try to create a dictionary I enter:
numbers = ('Bob':'322', 'Mary':'110', 'Joe':'839')
I get the error:
File "<stdin>", line 1
numbers = ('Bob':'322', 'Mary':'110', 'Joe':'839')
^
SyntaxError: invalid syntax
I've tried this in both the command line and in IDLE and the same error appears. What am I doing wrong? I really can't see it. Again sorry for low level of this question.
Dictionaries use curly braces {}, not parentheses ()
numbers = {'Bob':'322', 'Mary':'110', 'Joe':'839'}

Python - .format with {} touching other characters [duplicate]

This question already has answers here:
Str.format() for Python 2.6 gives error where 2.7 does not
(2 answers)
Closed 8 years ago.
I am trying to use the ".format" with a string to insert values in a for loop. This is what I'm trying to do:
with open('test.txt', 'w') as fout:
for element in range (0, 5):
line1 = 'Icon_{}.NO = Icon_Generic;'.format(element)
fout.write(line1)
When I do this it chokes. My best guess is that it doesn't like the underscore directly beside the {} ("_{}"). Is this correct? Is there a good workaround for this?
I have used something like this and it works:
line1 = Icon_Generic.NO = Icon_%02d.NO;\n' % element
However, if I want to do a large multiline bunch of code using the "% element" doesn't work well.
Thanks in advance!
EDIT: As best I can tell I'm using Python 3.3
This is the error I get (using IDLE 3.3.2 shell):
>>> with open('p_text.txt', 'w') as fout:
for element in range(0, 5):
template = """if (!Icon_{0}.notFirstScan) {""".format(element)
fout.write(template)
fout.write('\n\n')
input('press enter to exit')
Traceback (most recent call last):
File "<pyshell#13>", line 3, in <module>
template = """if (!Icon_{0}.notFirstScan) {""".format(element)
ValueError: Single '{' encountered in format string
It's the final opening brace that's given you the problem, as indicated by the error message: a "Single '{' encountered". If you need literal curly braces in the formatted string, you must escape them by doubling up ('{{') wherever you mean them to be literals:
template = """if (!Icon_{0}.notFirstScan) {{""".format(element)
^ escape the literal '{'
Note that this is true for closing curly braces (}) as well!
>>> print('{{{0}}}'.format('text within literal braces'))
{text within literal braces}

argv in python not working with windows executable cmdline [duplicate]

This question already has answers here:
How do I parse a string to a float or int?
(32 answers)
Closed 20 days ago.
in windows: I would like this program to run on commandline. However, I am getting an error. What am I doing wrong?
# create a method that append the letter stored in variable letter, ntimes.
import sys
def appender(letter,ntimes, sentence):
print sentence+(letter*ntimes)
appender(str(sys.argv[1]),sys.argv[2], str(sys.argv[3]))
The below is the error i get from command line in windows
C:\Users\QamarAli\Documents\afaq's stuff>appender.py "F" 10 "Hello this is sent"
Traceback (most recent call last):
File "C:\Users\QamarAli\Documents\afaq's stuff\appender.py", line 8, in <modul
e>
appender(str(sys.argv[1]),sys.argv[2], str(sys.argv[3]))
File "C:\Users\QamarAli\Documents\afaq's stuff\appender.py", line 5, in append
er
print sentence+(letter*ntimes)
TypeError: can't multiply sequence by non-int of type 'str'
C:\Users\QamarAli\Documents\afaq's stuff>
The error is pretty clear:
TypeError: can't multiply sequence by non-int of type 'str'
You're trying to multiply a sequence (in this case, a string) by something that isn't a number. Convert your argument to an integer:
appender(sys.argv[1], int(sys.argv[2]), sys.argv[3])
Also, sys.argv arguments are strings by default, so there's no need to explicitly convert them again.
The values in sys.argv are all strings. Instead of trying to convert some to strings, you need to convert the other ones to whatever non-string types you need. If you want the middle one to be an integer, call int on it.
All commandline arguments are seen by Python as strings.
Change your call to
appender(sys.argv[1], int(sys.argv[2]), sys.argv[3])

Categories

Resources