微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从python写入文件还会在最后一行添加其他字符

如何解决从python写入文件还会在最后一行添加其他字符

我有一个名为constants.py的python文件,其中包含以下内容

from pytestLoop.config.testdata_005_connect_for_bank_statements import *

xpath_username="//div[text()='"+uname+"']"
pswd="//div[@id='password']"

# this is the end of the file.

我还有一个名为alterConstants.py的python文件,其内容如下:

def changeConstants(fname):
    f = open("pytestLoop/config/constants.py",'r+')
    line = f.read()
    text=(line[line.index('config.') + 7:line.index(' import')])
    linenew = line.replace(text,fname)
    f.seek(0)
    f.write(linenew)
    f.close()

changeConstants("testdata_001")

执行上面的alterConstants.py文件之后,这就是constants.py

内容
from pytestLoop.config.testdata_001 import *

xpath_username="//div[text()='"+uname+"']"
pswd="//div[@id='password']"

# this is the end of the file.his is the end of the file.

我的最初目标是更改行from pytestLoop.config.testdata_005_connect_for_ban_statementsimport *,以导入我在changeConstants的{​​{1}}函数中传递的任何文件名,工作正常

但是python还会在alterConstants.py文件的最后一行写一些其他字符

  1. 有人可以解释为什么会发生这种情况吗?
  2. 也请提出如何解决此问题的建议。

谢谢。

解决方法

这不是在写多余的字符,而是在较大的旧文件中保留了原始字符。您需要将文件截断为新长度以删除多余的内容:

def changeConstants(fname):
    with open("pytestLoop/config/constants.py",'r+') as f:
        line = f.read()
        text = line[line.index('config.') + 7:line.index(' import')]
        linenew = line.replace(text,fname)
        f.seek(0)
        f.write(linenew)
        f.truncate()  # Trims file to match the current file offset

如果新文件数据较大,则truncate不会执行任何操作,但是当数据较短时,它将修剪文件以匹配写入新数据所产生的文件偏移量。

我还更改了您的代码,以使用with来管理文件生存期(无需显式关闭文件,并确保即使在处理过程中发生异常也可以关闭文件)。

,

与其重新找回文件的开头(不保留旧内容),而是再次打开文件以进行写入。

def changeConstants(fname):
    with open("pytestLoop/config/constants.py",'r') as f:
        line = f.read()
    text=(line[line.index('config.') + 7:line.index(' import')])
    linenew = line.replace(text,fname)
    with open("pytestLoop/config/constants.py",'w') as f:
        f.write(linenew)

以写入模式打开文件会自动替换旧内容。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。