Link to home
Start Free TrialLog in
Avatar of ReneGe
ReneGeFlag for Canada

asked on

Python 2.7 - Save to file

Hi there,

I want to output/append "print(int(argument2) + 100)" to the file name "text.txt"

import sys
args = sys.argv[1:]
if len(args) < 2:
    print("ERROR: at least 2 arguments required, but got only %d"  % len(args))
    sys.exit(1)

argument1, argument2  = args[:2]
argument2 = int(argument2)

print("argument1 %r" % argument1)
print("") #CLRF is intended here

print(int(argument2) + 100)

Open in new window


Thanks for your help,
Rene
ASKER CERTIFIED SOLUTION
Avatar of gelonida
gelonida
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ReneGe

ASKER

Thanks :)

Can you please explain:
-the %r in: print("argument1 %r" % argument1)
-"%d\n" and % in: fout.write("%d\n" % (int(argument2) + 100))

Thanks
Python has multiple ways of formatting variables to strings.

The 'old' way is using the % operator.
It is very similiar to the printf formatting of the C language.

the more 'modern' way is the format() method of string objects.

WIth the % operator you habe
 formatstring % (var1, var2, var3)

Open in new window


example:
a=1
b=2
print("A=%d B=%d and A+B=%d" % (a, b, a+b)) # the old % string format operatior
print("A={} B={} A+B={}".format(a, b, a+b)  # the newer more flexible, more complex format method

Open in new window


%d is for decimal numbers
%f for floating point numbers
%s for strings
%r for a representation of a variable

Open in new window

a=11
b="11"
print("a=%s and b=%s" % (a, b))  # results in a=11 and b=11
print("a=%r and b=%r" % (a, b))  # results in a=11 and b='11'

Open in new window


so if you use %r you can see, that a is a number and b is a string

more details about the % operator at https://docs.python.org/2/library/stdtypes.html#string-formatting

more details about the format() method at https://docs.python.org/2/library/string.html#format-string-syntax
Avatar of ReneGe

ASKER

Thank you sooo much for your explanation :)

Cheers!!!