-1

I am new to python and I tried to firstly create a new empty file with the help of python, for example:

f=open('new.txt','x') 

After creating this file, I wanted to write my output, which appears after running the code below, inside of the new.txt file:

for i in range(1,5): for j in range(0,i): print(i,end=' ') print('\n') 

However, I did not succeed with it using f.write function. Could you please advice me how to make it using f.write or another way?

Thanks in advance for your time and comprehension!

0

2 Answers 2

0
with open("new.txt", "w") as f: # opens a new file and gets you ready to write to it (hence the 'w', it stands for write) for i in range(1,5): for j in range(0,i): print(i,end=' ') f.write(f"{i} ") # write what you wanted to print print('\n') f.write("\n") # again write what you wanted to print # after this code executes python will automatically close the stream to the file (you do not need to do f.close() ) 

I left the prints in there so you can see what is being written to the file as well.

Sign up to request clarification or add additional context in comments.

Comments

0

I see you have created the file, to write, all you need to do is this:

with open('new.txt', 'a') as the_file: for i in range(1, 5): for j in range(0,i): the_file.write(str(i) + " ") the_file.write('\n') 

Let me break it down:

  1. The first line opens the txt file for you to write in it.
  2. Then you loop through and write what you want to write. Notice how I changed the fourth line to the_file.write(str(i)+" "). This is because you can only use strings inside the write() function.

Running this, you get:

1 2 2 3 3 3 4 4 4 4 

Inside your txt file. Hope you found this helpful :D

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.