8

Right now, I have file.py and it prints the word "Hello" into text.txt.

f = open("text.txt") f.write("Hello") f.close()

I want to do the same thing, but I want to print the word "Hello" into a Python file. Say I wanted to do something like this:

f = open("list.py") f.write("a = 1") f.close

When I opened the file list.py, would it have a variable a with a value 1? How would I go about doing this?

4
  • First of all you cannot write in file opened in read mode. Commented Dec 27, 2014 at 5:59
  • When you open it, it will have the text a = 1 in it (assuming you open it in write mode). Commented Dec 27, 2014 at 6:00
  • be careful with the 2nd code it doesn't close the file Commented Dec 27, 2014 at 7:24
  • Don't forget to add the newline at the end. write("a=1\n"). Commented Dec 27, 2014 at 16:05

3 Answers 3

6

If you want to append a new line to the end of a file

with open("file.py", "a") as f:
    f.write("\na = 1")

If you want to write a line to the beginning of a file try creating a new one

with open("file.py") as f:
    lines = f.readlines()

with open("file.py", "w") as f:
    lines.insert(0, "a = 1")
    f.write("\n".join(lines))
Sign up to request clarification or add additional context in comments.

Comments

1
with open("list.py","a") as f:
    f.write("a=1")

This is simple as you see. You have to open that file in write and read mode (a). Also with open() method is safier and more clear.

Example:

with open("list.py","a") as f:
    f.write("a=1")
    f.write("\nprint(a+1)")

list.py

a=1
print(a+1)

Output from list.py:

>>> 
2
>>> 

As you see, there is a variable in list.py called a equal to 1.

Comments

1

I would recommend you specify opening mode, when you are opening a file for reading, writing, etc. For example:

for reading:

with open('afile.txt', 'r') as f: # 'r' is a reading mode
    text = f.read()

for writing:

with open('afile.txt', 'w') as f: # 'w' is a writing mode
    f.write("Some text")

If you are opening a file with 'w' (writing) mode, old file content will be removed. To avoid that appending mode exists:

with open('afile.txt', 'a') as f: # 'a' as an appending mode
    f.write("additional text")

For more information, please, read documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.