coxel
coxel

Reputation: 13

How to save results in txt file but not the same like print?

Hi with this code I get numbers.

n = 1000

while n > 500:
    print(n, end=', ')
    n -= 50
    print(n)
    n -= 100

I get this result

1000, 950
850, 800
700, 650
550, 500

How I can save this in txt but this way? First number to be second and second to be first.

950, 1000
800, 850
650, 700
500, 550

I tried this but not work

f = open("test.txt", 'w')
print(n, end=', ', file=f)
print(n, file=f)
f.close() 

And tried this

with open("test.txt", 'w') as f:
   print('Filename:', filename, file=f)

Can someone to help me?

Upvotes: 1

Views: 63

Answers (3)

Spencilian
Spencilian

Reputation: 11

A quick google search give a nice source from w3 schools. https://www.w3schools.com/python/python_file_write.asp

To summarize:

You need to replace the

print(n, end=', ', file=f)

with

f.write("Add your info here")

Doing this with the with thing:

with open("your_file.txt", "w") as f:
    f.write("The stuff you want in the file here")

You can also read from a file with the appropriately named read() command

f = open("your_file.txt", "r")
f.read()

Upvotes: 0

sal
sal

Reputation: 3593

There are many ways this can be done, but the way I would go is to calculate the two numbers and format the string you want to write to file first. Something like this:

f = open("test.txt", 'w')
n = 1000
while n > 500:
    second = n    # second number to print
    first = n - 50   # first number to print
    f.write('%d,%d\n' % (first, second))   # print to file
    n -= 150          # decrement for the total of 150 per round
f.close() 

Upvotes: 2

iScripters
iScripters

Reputation: 421

This is a pretty ugly example but might be easier to understand this way.

n = 10000

with open('test.txt', 'w') as f:
  while n > 500:
    tmp = []
    tmp.append(n)
    n -= 50
    tmp.append(n)
    n -= 100
    print(tmp[1], tmp[0])
    f.write(f"{tmp[1]}, {tmp[0]}\n")

Upvotes: 0

Related Questions