6

I would like to know how to overwrite a file in python. When I'm using "w" in the open statement, I still get only one line in my output file.

article = open("article.txt", "w")
article.write(str(new_line))
article.close()

Can you tell me please how can I fix my problem?

martineau
  • 119,623
  • 25
  • 170
  • 301
Python_newbie
  • 73
  • 1
  • 1
  • 4
  • 2
    Why do you think there's a problem? If you're overwriting the file, there *should* only be one line in the output. If you want to *`a`dd* to the file, why open it in over`w`rite mode? – jonrsharpe Jan 15 '17 at 23:44

2 Answers2

3

If you are in fact looking to overwrite the file line by line, you'll have to do some additional work - since the only modes available are read ,write and append, neither of which actually do a line-by-line overwrite.

See if this is what you're looking for:

# Write some data to the file first.
with open('file.txt', 'w') as f:
    for s in ['This\n', `is a\n`, `test\n`]:
        f.write(s)

# The file now looks like this:
# file.txt
# >This
# >is a
# >test

# Now overwrite

new_lines = ['Some\n', 'New data\n']
with open('file.txt', 'a') as f:
    # Get the previous contents
    lines = f.readlines()

    # Overwrite
    for i in range(len(new_lines)):
        f.write(new_lines[i])
    if len(lines) > len(new_lines):
        for i in range(len(new_lines), len(lines)):
            f.write(lines[i])

As you can see, you first need to 'save' the contents of the file in a buffer (lines), and then replace that.

The reason for that is how the file modes work.

deepbrook
  • 2,523
  • 4
  • 28
  • 49
0

"overwrite" is a strange term; especially since you expect to see more than one line from the above code

I am guessing you mean something like "write beyond". The word for that would be "append' and you would want 'a' instead of 'w'.