Arrrr 发表于 2022-7-16 20:36:03

删除txt文件的偶数行报错:AttributeError: 'str' object has no attribute 'readl..

想用readlines()和del函数删除txt文档的偶数行
代码如下

file1="/Users/ar/Desktop/1/out_test/kai1.txt"
lines=file1.readlines()
del lines


报错
AttributeError: 'str' object has no attribute 'readlines'
{:5_92:}求大神帮助!

临时号 发表于 2022-7-16 21:01:35

f = open("/Users/ar/Desktop/1/out_test/kai1.txt","r")
line = f.readlines()
f.close()
count = 0
for i in range(len(line)):
    if i % 2 == 1:
      line = ''
      count += 1
for i in range(count):
    line.remove('')
f = open("/Users/ar/Desktop/1/out_test/kai1.txt","w")
f.writelines(line)
f.close()

jackz007 发表于 2022-7-17 00:35:28

本帖最后由 jackz007 于 2022-7-17 01:00 编辑

s , c = '' , 0
with open("/Users/ar/Desktop/1/out_test/kai1.txt") as fp:
    for x in fp:
      if not c % 2:
            s += x
      c += 1
with open("/Users/ar/Desktop/1/out_test/kai1_new.txt" , "w") as fp:
    fp . write(s)

wp231957 发表于 2022-7-17 06:53:46

纯文本文件的file对象才有readlines方法
页: [1]
查看完整版本: 删除txt文件的偶数行报错:AttributeError: 'str' object has no attribute 'readl..