简体   繁体   中英

what is wrong here in this python code?

What is wrong here in this code: I am just passing an existing file and then removing it using os.remove() and then writing it with another content. But the file shows the previous content not updated one. Snippet here:

#!/usr/bin/env python
import sys
import os

arg1=sys.argv[1]
_list = ['a', 'b', 'c']
os.remove(arg1)
hd = open(arg1, 'w')
for line in _list:
    hd.write(line)
hd.close()

Let's say my file contains the following content: output1 :

p
q
r
s

After removing the file( os.remove() ), re-creating the same file and over-writing it's content from the list. The expected output:

a
b
c

But I am getting output1 instead of expected output.

You may simply want to open the file and write the current content without removing the file first:

with open(arg1, "w") as f:
    for line in _list:
        f.write(line)

This is how open() works.

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it's omitted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM