7

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?

Elle Nolan
  • 379
  • 5
  • 8
  • 22

3 Answers3

5

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))
Greg
  • 5,422
  • 1
  • 27
  • 32
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.

GLHF
  • 3,835
  • 10
  • 38
  • 83
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.

Fomalhaut
  • 8,590
  • 8
  • 51
  • 95