>>> dir(file) ['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
[code]learn python http://qiwsir.github.io qiwsir@gmail.com[/code]此文件以供三行。 下图显示了这个文件的存储位置: [img]http://files.jb51.net/file_images/article/201409/201409281534455.png[/img] 在上面截图中,我在当前位置输入了python(我已经设置了环境变量,如果你没有,需要写全启动python命令路径),进入到交互模式。在这个交互模式下,这样操作:
>>> f = open("130.txt") #打开已经存在的文件
>>> for line in f:
... print line
...
learn python
http://qiwsir.github.io
qiwsir@gmail.com
>>> f = open('130.txt')
>>> for line in f:
... print line, #后面加一个逗号,就去掉了原来默认增加的\n了,看看,少了空行。
...
learn python
http://qiwsir.github.io
qiwsir@gmail.com
>>> f = open('130.txt')
>>> for line in f:
... print line,
...
learn python
http://qiwsir.github.io
qiwsir@gmail.com
>>> for line2 in f: #在前面通过for循环读取了文件内容之后,再次读取,
... print line2 #然后打印,结果就什么也显示,这是什么问题?
...
>>>
>>> f = open("130.txt")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '130.txt'
>>> f = open("./codes/130.txt") #必须得写上路径了(注意,windows的路径是\隔开,需要转义。对转义符,看官看以前讲座)
>>> for line in f:
... print line
...
learn python
http://qiwsir.github.io
qiwsir@gmail.com
>>>
>>> nf = open("131.txt","w")
>>> nf.write("This is a file")
>>> f = open("130.txt")
>>> f
<open file '130.txt', mode 'r' at 0xb7530230>
>>> f = open("130.txt","r")
>>> f
<open file '130.txt', mode 'r' at 0xb750a700>
>>> fp = open("131.txt")
>>> for line in fp: #原来这个文件里面的内容
... print line
...
This is a file
>>> fp = open("131.txt","w") #这时候再看看这个文件,里面还有什么呢?是不是空了呢?
>>> fp.write("My name is qiwsir.\nMy website is qiwsir.github.io") #再查看内容
>>> fp.close()
$ cat 131.txt #cat是linux下显示文件内容的命令,这里就是要显示131.txt内容 My name is qiwsir. My website is qiwsir.github.io
>>> fp = open("131.txt","a")
>>> fp.write("\nAha,I like program\n") #向文件中追加
>>> fp.close() #这是关闭文件,一定要养成一个习惯,写完内容之后就关闭
$ cat 131.txt My name is qiwsir. My website is qiwsir.github.io Aha,I like program
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有