麻烦各位帮我看看这几行代码如何解决报错
list1 = []file1 = open("txt1.txt" , "a")
for i in file1:
if "1" in i:
i = i.replace("1", "2")
list1.append(i)
file1.writeline(list1)
file1.close()
代码如上。这是我想将文件txt1.txt内的1全部替换为2,但却在for i in file1这里报错了,io.UnsupportedOperation: not readable,有大佬知道应该怎么解决吗? list1 = []
file1 = open("txt1.txt" , "a")#文件名没有路径?路径错误就找不到文件啊
for i in file1: #就报错不可读咯?
if "1" in i:
i = i.replace("1", "2")
list1.append(i)
file1.writeline(list1)
file1.close() 1. file1 = open("txt1.txt" , "a")要改成"a+","a"是只写,不能读取
2. file1.writeline(list1)改成writelines 冬雪雪冬 发表于 2020-10-19 23:23
1. file1 = open("txt1.txt" , "a")要改成"a+","a"是只写,不能读取
2. file1.writeline(list1)改成writel ...
除了这两个问题外,是不是以a或者a+模式打开文件后,文件指针会指向文件末尾。
所以直接for i in file1会读不到任何内容。
是不是应该打开后把文件指针指向文件开头。file1.seek(0) zhaosiyu29 发表于 2020-10-20 09:34
除了这两个问题外,是不是以a或者a+模式打开文件后,文件指针会指向文件末尾。
所以直接for i in file1 ...
CharacterMeaning
'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of the file if it exists
'b'binary mode
't'text mode (default)
'+'open a disk file for updating (reading and writing)
1.是的
2.昨天的回答有误,如果想替换,打开文件的模式是"r+",并读取后再seek(0,0)
冬雪雪冬 发表于 2020-10-19 23:23
1. file1 = open("txt1.txt" , "a")要改成"a+","a"是只写,不能读取
2. file1.writeline(list1)改成writel ...
谢谢解答! zhaosiyu29 发表于 2020-10-20 09:34
除了这两个问题外,是不是以a或者a+模式打开文件后,文件指针会指向文件末尾。
所以直接for i in file1 ...
谢谢!
页:
[1]