Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中将空字符串写入文本文件_Python_File Io - Fatal编程技术网

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

在Python中将空字符串写入文本文件,python,file-io,Python,File Io,这是一个相当尴尬的问题,尽管我来自web开发,很少需要处理文件i/o 我编写了一个简单的配置更新程序,用于我的共享主机。它扫描目录中的子目录,然后将配置行写入文件,每个子目录一行。问题是,当它检测到有配置行但没有子目录时,它应该将config留空——这不起作用!带着这个来这里,因为文档没有提到它,谷歌也没有帮助。其Python 2.6.6基于Debian Lenny file = open('path', 'r+') config = file.read() ## all the code in

这是一个相当尴尬的问题,尽管我来自web开发,很少需要处理文件i/o

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

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()

在这种情况下,文件根本不会更改。有趣的是,让它忘记配置而只做文件。write(“”)也不会清空文件,而是将\n放在行的看似随机的位置。

您可能需要在
打开
调用中使用
'w+'
模式来截断文件。

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

尝试:


如果要清空文件,请使用:


我已经更新了脚本并使用了ars的答案,但您的答案在本例中是正确的。谢谢
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()
f.truncate(0)
f.close()