对象没有试图读取文件的“replace”属性。tx

2024-05-02 04:21:35 发布

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

在你说它是复制品之前。。。我已经读了至少15个其他的答案,但还是没能。。。

我在尝试替换特定行时开始出现此错误。 现在它告诉我它没有replace属性。。。在某个时候

每次确定的事件发生时,我只需要将+1添加到特定行。。。试过这个。。这可能是一个粗略的解决方案。

每次当他们创建一个新文件时,我都看到一些答案,这是不可能的,因为这个事件应该一直发生

所以我要问的是。。。为什么replace函数不起作用。。。和/或如果我在做什么还有一个更简单的函数。

代码:

usercidFile = str(usercid) +".txt"

with open(usercidFile,'r+') as uf:
    lines = uf.readlines()

    xName = str(lines[1])
    x = lines[4]    
    xx = lines[2]
    y = int(x)+1
    #it prints all vars until this point
    uf = uf.replace(str(x),str(y))

◙◙◙这将导致以下错误:

  File "/home/ubuntu/workspace/bot.py", line 49, in listener
uf = uf.replace(str(x),str(y))
AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'

Tags: 文件函数答案属性错误事件解决方案replace
3条回答

你想做的事在任何语言中都是不实际的。

首先,正如其他人所说,文件对象上没有replace()方法。

更重要的是你似乎不明白文本文件是如何工作的。你说:“每当他们创建一个新文件时,我都看到一些答案。”。你考虑过他们为什么这么做吗?

“我只需要将+1添加到特定行”

让我们在文本文件中取几行,您认为看起来像这样:

onetwomumble9
threefourmumble3

但是文本文件没有什么特别的,它只是从第一个字节到最后一个字节,换行显示行的结束位置。看起来真的是这样:

onetwomumble9\nthreefourmumble3\n

其中,\n表示单个换行符。

假设你用10替换了9,用4替换了3。问题是109宽,额外的字符将覆盖后面的换行符(或任何其他字符)。所以你的结局是:

onetwomumble10threefourmumble4\n

你输了!

这就是为什么你必须复制文件来更新它!另一种方法是使用处理这些问题的数据库(如SQLite)。

有一些解决办法。最简单的方法是确定字符的绝对最大数量,并用零填充,例如0009将更新为0010

假设文件如下所示:

onetwomumble0009
threefourmumble0005
sixsevenmumble0067
eightnonemumber0042

对于同一个文件的读写,必须自己维护文件的位置。当你读一行时,它把当前的位置放在下一行,所以要重写一行,你必须把它移回去。 示例代码:

import re
import sys

# Could be done as a one-line lambda, but would be difficult to read
def addit(m):
    num = m.groups()[0]
    new_num = "%04d" % (int(num) + 1)
    return new_num

line_number = 1

with open('gash.txt', 'r+') as uf:
    while True:
        start_pos = uf.tell()  # Get start of line position
        line = uf.readline()
        if not line : break
        end_pos = uf.tell()  # Get end of line position - needed if updating more than one line

        # Let's say we update line 2, and we decided on 4 chars
        if line_number == 2: 
            # Do the add
            newline = re.sub(r'(\d{4})$', addit, line)


            # Sanity check
            if len(newline) != len(line):
                print("line length changed!", line, file=sys.stderr)
                sys.exit(1)

            # Seek to start of line just read and write
            uf.seek(start_pos)
            uf.write(newline)
            # Seek to start of next line
            uf.seek(end_pos)

            # If we only wanted to update one line, we can:
            break

        line_number += 1

问题是您试图对一个file对象调用replace方法,而这是一个string方法。

事实上:

>>> f = open('test.txt', 'r+')                                                                                   
>>> type(f)
<type 'file'>
>>> f.replace('test', 'no_test')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'file' object has no attribute 'replace'
>>> 'this is a test'.replace('test', 'no_test')
'this is a no_test'

显然,一个_io.TextIOWrapper即一个文件对象不会有一个替换方法,它是一个字符串函数。我想你是想替换整个文件。这里有一个快速的解决方法。

file_data = ''.join(lines)
# Now apply your replacements here
file_data = file_data.replace(str(x),str(y))  

相关问题 更多 >