设为首页 加入收藏

TOP

Python Base Four(一)
2017-09-30 17:19:01 】 浏览:3717
Tags:Python Base Four

35. In python, file operation syntax is similar to c.

      open(file,'r',……) //the first parameters is necessary, other is optional ,the second parameters is 'r' by default

      if you want to open a file, you can use:

      f = open('//Users//wyg_mac//Desktop//Account.txt') //if you don't know the path ,you can drag the file to console

      if you want to close file ,you can use:

      f.close()

      next now that we know how to open file and close file ,but how to read file content.

      you can use

      f.read(size = -1) //read size buffer, if size not define or  minus ,read next buffer , and return as string

      f.readline() //open as write mode, if file exist, append at end

      if you want to write content to file ,how to achieve it.

      f.wirte(str) // put str write file

      f.wirtelines(seq) //

      f.tell() // return current position

      f.seek(offset,from) //from( if is 0, start position,1 current position 2 end position) offset

      such as if i want to create a file demo.txt on desktop and write content whth 'write code change world'

      f = open(r'/users/wyg_mac/desktop/demo.txt','w')

      f.wirte('write code change world')

      f.close()

      there are something we need to notice:

      if a file not exist , as follow ,it will have error:

      f = open(r'/users/wyg_mac/desktop/a.txt')  -> error

      if file not exist ,you use follow it will be right:

      f = open(r'/users/wyg_mac/desktop/a.txt') -> right

 

//seventh day to study python

36. In python , os module is base and important. 

      import os

      os.getcwd()  //get current file path

      -> '/users/wyg_mac/documents'

      os.chdir('/users/wyg_mac/desktop')  //change file path

      os.getcwd()

      -> '/users/wyg_mac/desktop

      os.listdir('/users/wyg_mac/desktop')  //list file dir

      -> ['demo.txt', '.DS_Store',]

      os.mkdir('/users/wyg_mac/desktop/a') 

      -> create a file named a

      os.mkdir('/users/wyg_mac/desktop/a/b')

      -> if file a exist ,create file named b in file a, if a not exist ,will have an error

      os.makedirs('/users/wyg_mac/desktop/m/n/o')

      -> create file m on desktop , m include n , n include o

      if file m/n/o ,o include ttt.txt

      os.remove('/users/wyg_mac/desktop/m/m/o/ttt

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python 基础 字符串拼接 + if whi.. 下一篇[python学习笔记]Day1

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目