一、原则:
文本文件的所有数据的输入和输出都是字符串(string)!
注意:对字符串的换行符的处理!
二、函数:
1. open ( filepath, mode):
- 打开路径为filepath的文件;
- mode为‘w'时,表示该文件为输出文件,用于“写”,原文件存在数据均被擦除;若该文件不存在则创建该文件;
- mode为'r'时,表示该文件为输入文件,用于“读”,若该文件不存在则会产生错误。
2. f.write(S):
- 将字符串S写入文件f,因此,若写入的是其他类型数据,需先转换为字符串。
3. f.read():
- 将文件f的所有内容作为单独字符串读取出来;若包含多行文本,换行符将会嵌入到该字符串中;
- 若包含多行文本,还可以用:
- for line in f:直接按行读取;
- 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用//而非\,因为\是转义符!