无法使用python更新另一个文件中的数据

2024-03-29 02:27:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python写了一个脚本。现在,我打开了现有的文件并用另一个值替换它的值。值在其他文件中被替换但不更新。你知道吗

with open ("VAdminTool.properties", "r+") as propfile:
   data1=propfile.read().splitlines()
   listin1 = len (data1)
   for line1 in data1:
     line2 = line1.split('=')
     line2[0] = line2[0].strip()
     if line2[0] == 'YPSAddress':
       line2[1] = line1.replace(line2[1],yps_url)
       print line2[1]
       propfile.write(line2[1])
   propfile.close()

Tags: 文件脚本readlenaswithpropertiesopen
1条回答
网友
1楼 · 发布于 2024-03-29 02:27:02

在这样的地方修改文件时必须非常小心。修改后的文本必须与原始文本大小完全相同,否则会造成混乱。如果替换文本的大小不正确,文件中的以下字节将不会神奇地移动。你知道吗

但是如果没有看到您的数据,就无法判断这是否是代码的问题。你知道吗

但是,您的代码没有在正确的位置编写新文本,这是一个问题。你不能只在当前位置写新的文本,你需要seek()到正确的位置。下面的代码显示了两种稍微不同的处理方法。它可以for line in f:循环中完成,但是我认为用一个简单的while True:循环来完成它稍微干净一些。你知道吗

#!/usr/bin/env python

""" Inplace file update demo

    Written by PM 2Ring 2015.08.20

    See http://stackoverflow.com/q/32096531/4014959
"""

def create(fname):
    data = 'zero one two three four five six seven eight nine'
    with open(fname, 'w') as f:
        for s in data.split():
            f.write(s + '\n')

def modify0(fname):
    with open(fname, 'r+') as f:
        fpos = 0
        for line in f:
            print repr(line)
            outline = line[:2].upper() + line[2:]
            f.seek(fpos)
            f.write(outline)
            fpos += len(line)
            f.seek(fpos)

def modify1(fname):
    with open(fname, 'r+') as f:
        while True:
            fprev = f.tell()
            line = f.readline()
            if not line:
                break
            print repr(line)
            f.seek(fprev)
            outline = line[:2].upper() + line[2:]
            f.write(outline)

def show(fname):
    with open(fname, 'r') as f:
        for line in f:
            print repr(line)

modify = modify1
fname = 'testfile.txt'

create(fname)
modify(fname)
print '\n' + 20*' - ' + '\n'
show(fname)

输出

'zero\n'
'one\n'
'two\n'
'three\n'
'four\n'
'five\n'
'six\n'
'seven\n'
'eight\n'
'nine\n'

 -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - 

'ZEro\n'
'ONe\n'
'TWo\n'
'THree\n'
'FOur\n'
'FIve\n'
'SIx\n'
'SEven\n'
'EIght\n'
'NIne\n'

相关问题 更多 >