我有以下代码:
import re
#open the xml file for reading:
file = open('path/test.xml','r+')
#convert to string:
data = file.read()
file.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
file.close()
Run Code Online (Sandbox Code Playgroud)
我想用新内容替换文件中的旧内容.但是,当我执行我的代码时,附加了文件"test.xml",即我将旧的内容与新的"替换"内容相对应.我该怎么做才能删除旧的东西,只保留新的东西?
gue*_*tli 69
如果你想做就地替换你需要使用truncate:https://docs.python.org/3/library/os.html?highlight =
struncate#os.truncate或者你使用seek
.这将删除旧文件并创建一个新文件.
AFAIK truncate不会更改inode,但open(...,'w')将创建一个新的inode.但在大多数情况下,这并不重要.......我现在测试了.open(...,'w')和truncate()都不会更改文件的inode编号.(测试两次:一次使用Ubuntu 12.04 NFS,一次使用ext4).
顺便说一下,这与Python并不真正相关.解释器调用相应的低级API.该方法file.truncate()
在C编程语言中的工作方式相同:请参阅http://man7.org/linux/man-pages/man2/truncate.2.html
Chi*_*cob 18
file='path/test.xml'
with open(file, 'w') as filetowrite:
filetowrite.write('new content')
Run Code Online (Sandbox Code Playgroud)
以“ w”模式打开文件,您将能够替换其当前文本,并使用新内容保存文件。
ser*_*inc 13
使用truncate()
,解决方案可能是
import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
#convert to string:
data = f.read()
f.seek(0)
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
f.truncate()
Run Code Online (Sandbox Code Playgroud)
小智 6
import os#must import this library
if os.path.exists('TwitterDB.csv'):
os.remove('TwitterDB.csv') #this deletes the file
else:
print("The file does not exist")#add this to prevent errors
Run Code Online (Sandbox Code Playgroud)
我遇到了类似的问题,我没有使用不同的“模式”覆盖现有文件,而是在再次使用它之前删除了该文件,这样就好像我在每次运行代码时都附加到一个新文件。
归档时间: |
|
查看次数: |
164442 次 |
最近记录: |