简体   繁体   English

这个Python代码在这里出了什么问题?

[英]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. 这段代码在这里有什么问题:我只是传递一个现有文件,然后使用os.remove()删除它,然后用其他内容编写它。 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 : 假设我的文件包含以下内容: 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. 删除文件( os.remove() )后,重新创建相同的文件并覆盖列表中的内容。 The expected output: 预期输出:

a
b
c

But I am getting output1 instead of expected output. 但是我得到的是output1而不是预期的输出。

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. 这就是open()的工作方式。

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; 当仅读取文件时,模式可以为“ r”,仅用于写入时为“ w”(具有相同名称的现有文件将被删除),并且“ a”打开文件以进行附加; any data written to the file is automatically added to the end. 写入文件的所有数据都会自动添加到末尾。 'r+' opens the file for both reading and writing. “ r +”打开文件以供读取和写入。 The mode argument is optional; mode参数是可选的; 'r' will be assumed if it's omitted. 如果省略,则假定为“ r”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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