鱼C论坛

 找回密码
 立即注册
查看: 2004|回复: 3

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

[复制链接]
发表于 2022-7-16 20:36:03 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

file1="/Users/ar/Desktop/1/out_test/kai1.txt"
lines=file1.readlines()
del lines[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41]


报错
AttributeError: 'str' object has no attribute 'readlines'
求大神帮助!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 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[i] = ''
        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()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 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)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-7-17 06:53:46 From FishC Mobile | 显示全部楼层
纯文本文件的file对象才有readlines方法
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-8 13:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表