关于文件写入后自动换行的问题
请教各位大神,我自己写了一段网址抓取的小代码,并用添加的方式写入txt文件:with open("Url_base.txt", "a") as f:
f.write(cctv)
那么现在问题来了,运行程序后得到如下格式的文本:
http://tv.cctv.com/lm/zgylc/zs/index.shtmlhttp://tv.cctv.com/lm/zgylc/zs/index.shtmlhttp://app.cctv.com/appkhdxz/ydb/index.shtmlhttp://app.cctv.com/appkhdxz/ysxwydb/index.shtmlhttp://app.cctv.com/appkhdxz/xmpdydb/index.shtmlhttp://tv.cctv.com/http://dianshiju.cctv.com/special/rmjcg/shouye/http://dianshiju.cctv.com/special/rmjcg/shouye/#http://tv.cctv.com/lm/yfdj/http://tv.cctv.com/2016/09/02/ARTIyxh7h9QqIJDL2iUtI0WZ160902_10.shtmlhttp://tv.cctv.com/lm/2016wyscw/index.shtmlhttp://tv.cctv.com/lm/duihuahttp://tv.cctv.com/2016/09/11/VIDEr1UZVDQ5dBZwvTpeNEKq160911.shtmlhttp://tv.cctv.com/lm/zgylc/shouye/http://tv.cctv.com/2016/09/11/VIDEKek1KEkwfYURIDdoxuwp160911.shtmlhttp://tv.cctv.com/lm/jyxwl/http://tv.cctv.com/2016/09/11/VIDEII9IwWVj5NjPMSR2OuhY160911.shtmlhttp://tv.cctv.com/cctv3/zqwh2016/index.shtmlhttp://tv.cctv.com/lm/yfdjhttp://tv.cctv.com/2016/09/09/VIDEUIy5KjcxpxWLXMxtdF6J160909.shtmlhttp://tv.cctv.com/lm/jkzlhttp://tv.cctv.com/2016/09/11/VIDEfJbFxNustTkD6z4hDqXP160911.shtmlhttp://tv.cctv.com/lm/2016wyscw/index.shtmlhttp://tv.cctv.com/2016/09/11/VIDEwXdfNkkwFLJDA1Pd0irF160911.shtmlhttp://www.cctv.com/gyys/index.shtmlhttp://www.cctv.cnhttp://www.cctv.com/2016/09/07/ARTI8FLqKCxFXWKcivAbQyO1160907.shtmlhttp://www.cctv.com/2016/09/07/ARTI8FLqKCxFXWKcivAbQyO1160907.shtml#http://www.cctv.com/2016/09/09/ARTI7yUmMhIni8eYPatcftsB160909.shtmlhttp://www.cctv.com/2016/09/09/ARTIxTTDmkfKAnj95ByjsFIk160909.shtmlhttp://news.cctv.com/video/index.shtml#http://tv.cctv.com/2016/09/12/VIDEhYVGAvdBpqqrjfoRrCaB160912.shtmlhttp://tv.cctv.com/2016/09/12/VIDEhYVGAvdBpqqrjfoRrCaB160912.shtmlhttp://tv.cctv.com/2016/09/12/VIDEKdoEfuLDbPthyLlXRgu9160912.shtmlhttp://tv.cctv.com/2016/09/12/VIDEKdoEfuLDbPthyLlXRgu9160912.shtmlhttp://tv.cctv.com/2016/09/12/VIDEFQZQX6MJy0NpmnoTY2l0160912.shtmlhttp://tv.cctv.com/2016/09/12/VIDEFQZQX6MJy0NpmnoTY2l0160912.shtmlhttp://tv.cctv.com/2016/09/12/VIDEOXwfF6S6s07ZPNvc4GFp160912.shtmlhttp://tv.cctv.com/2016/09/12/VIDEOXwfF6S6s07ZPNvc4GFp160912.shtml
有什么方法可以实现让文本自动分割并换行? 用字符串的替换方法(replace)。将http替换为\nhttp 试过了,替换完以后文本还是“shtml\nhttp://”这样,并没有认出换行符。难道是编码问题? @-@
with open("Url_base.txt", "a") as f:
f.writeline(cctv)
SixPy 发表于 2016-9-13 12:10
试过了,出错{:7_119:}
Traceback (most recent call last):
File "C:\Python34\demo\test.py", line 30, in <module>
f.writeline(cctv)
AttributeError: '_io.TextIOWrapper' object has no attribute 'writeline'
jerryxjr1220 发表于 2016-9-13 19:45
试过了,出错
那就自己加换行符~
with open("Url_base.txt", "a") as f:
f.write(cctv+ '\r\n')
或者:
with open("Url_base.txt", "a") as f:
print(cctv, file=f)
果然可以了,谢谢大神!
后一种方法{:7_146:} 能否实现每输入一定的个数再换行,比如我要实现输入4个就换行一次 jerryxjr1220 发表于 2016-9-13 20:38
果然可以了,谢谢大神!
后一种方法
我的第一个想法是,用正则匹配出来每个链接,然后依次写入 苦瓜海绵 发表于 2017-6-13 23:49
能否实现每输入一定的个数再换行,比如我要实现输入4个就换行一次
输入1个或者4个或者n个,都可以用正则来搞定 SixPy 发表于 2016-9-13 20:23
那就自己加换行符~
或者:
第一种可以,谢谢兄弟
页:
[1]