Home > OS >  pattern in file python
pattern in file python

Time:11-06

I got stuck again.

I want to write a pattern into file in python.

Like this one, for example

rows = 3
for i in range(rows 1):
    for j in range(i):
        print(i, end=' ')
    print('')

So, I tried to do it with

f = open("file.txt", "w")
f.write(...)
f.close()

But it gives an error. Did anyone try to put a pattern in a file in python? Thank you!

CodePudding user response:

print() automatically converts its arguments to strings, but f.write() doesn't perform this automatic conversion, so you need to do it explicitly.

rows = 3
with open("file.txt", "w") as f:
    for i in range(rows 1):
        f.write(f"{i} " * i)
        f.write("\n")

You could also keep your original code, and simply use the file=f optional argument to print().

rows = 3
with open("file.txt", "w") as f:
    for i in range(rows 1):
        for j in range(i):
            print(i, end=' ', file=f)
        print('', file=f)
  • Related