python - 在 Python 中将空字符串写入文本文件

标签 python file-io

相当尴尬的问题,虽然我来自网络开发,很少需要处理文件输入/输出。

我写了一个简单的配置更新程序用于我的共享主机。它扫描子目录的目录,然后将配置行写入文件 - 每个子目录一行。问题是,当它检测到有配置行但没有子目录时,它应该将配置留空——这是行不通的!带着这个来到这里是因为文档没有提到它而且谷歌也没有帮助。 Debian Lenny 上的 Python 2.6.6。

file = open('path', 'r+')
config = file.read()
## all the code inbetween works fine
## config is .split()-ed, hence the list
if config == ['']:
    config = ''
file.write(config)
file.close()

在这种情况下,文件根本没有改变。有趣的是,让它忘记配置而只执行 file.write('') 也不会清空文件,而是将\n 放在该行看似随机的位置。

最佳答案

您正在使用 r+ 读写模式。所有读取和所有写入都会更新文件的位置。

尝试:

file = open('path', 'r+')
config = file.read()
## all the code inbetween works fine
## config is .split()-ed, hence the list
if config == ['']:
    config = ''
file.seek(0)    # rewind the file
file.write(config)
file.close()

关于python - 在 Python 中将空字符串写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3919382/

相关文章:

c - 将字符串写入文件会产生奇怪的字符

c - 从不断更新的文件中读取

Java NIO MappedByteBuffer 内存溢出异常

python - <键入 'exceptions.NameError' >

python - 如果为真 : turn following values to True in list of booleans until nth position after True is reached

python - 修改 os.stat 对象

python - mysqldb 数据库主机未被接受?

python - VSCode 中的任务输出编码

php - PHP 中的文件 IO 不起作用

c++ - 什么会延迟 VxWorks 任务的抢占?