julley 发表于 2018-8-9 12:57:38

Python学习之文件操作

#/usr/bin/python  

  
content='''\                      #这里使用'''
  
This is
  
a test file
  
for python
  
'''
  
f=file('content.txt','w')            #以写的方式打开content.txt,可以创建一个空文件
  
f.write(content)                     #将content的内容写入到content.txt文件中
  
f.close                              #关闭文件
  

  
f=file('content.txt','r')            #以只读的方式打开文件
  
line=f.read()                        #读出文件的内容
  
print line,                        #print这里加了一个逗号,防止python读完最后一行后自动添加一行空行
  
f.close()
  

  
print "\n"
  

  
f=file('content.txt')               #默认以只读的方式打开
  
while True:
  
      line=f.readline()               #读文件的每行内容
  
      if len(line)==0:                #如果一行的长度为0,表示读完了所有的行
  
         break                        #break跳出while循环
  
      print line,
  
f.close()
页: [1]
查看完整版本: Python学习之文件操作