python学习笔记:文件IO

一、原则:

文本文件的所有数据的输入和输出都是字符串(string)

注意:对字符串的换行符的处理!

二、函数:

1. open ( filepath, mode):

  • 打开路径为filepath的文件;
  • mode为‘w'时,表示该文件为输出文件,用于“写”,原文件存在数据均被擦除;若该文件不存在则创建该文件;
  • mode为'r'时,表示该文件为输入文件,用于“读”,若该文件不存在则会产生错误。

2. f.write(S):

  • 字符串S写入文件f,因此,若写入的是其他类型数据,需先转换为字符串。

3. f.read():

  • 将文件f的所有内容作为单独字符串读取出来;若包含多行文本,换行符将会嵌入到该字符串中;
  • 若包含多行文本,还可以用:
  1. for line in f:直接按行读取;
  2. f.readline():读取一行字符串(包含换行符);当遇到文件末尾时,返回空字符串。

4. f.close():

  • 与open对应,及时关闭文件,若未关闭则会导致数据丢失。
path="F://myfile.txt"

# open and write
f=open(path,'w')
f.write("First line.\nSecond line.\n")  # the file will has two lines: First line.
f.close()                               # Second line.

# open and read
f=open(path,'r')
text=f.read()                    # text="First line.\nSecond line.\n"
f.close()

# open and "for"
f=open(path,'r')
for line in f:                   # output: First line.
    print(line)                  # Second line.

# open and readline
f=open(path,'r')
while True:                      # output: First line.
    line=f.readline()            # Second line.
    if line="": break
    print(line)     

三、创建函数:

1. 读取文件内容:

def readFile(path):
    with open(path,"rt") as f:
        return f.read()

2. 写入文件内容:

def writeFile(path,contents):
    with open(path, "wt") as f:
        f.write(contents)

注意:path用//而非\,因为\是转义符!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值