使用open()函数打开文件,参数传要打开的文件的名称。Python在当前执行的文件所在的目录中查找指定的文件。
文件不与程序文件位于相同目录下的时候,需要提供文件路径.linux系统下文件路径使用用斜杠/,windows下使用反斜杠\。
#关键字with在不再需要访问文件后将其关闭
with open('pi_digits.txt') as file_object:
#read()方法读取文件的全部内容
contents = file_object.read()
print(contents)
#rstrip()方法删除字符串末尾多余出来的空白
print(contents.rstrip())
#逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
#创建一个包含文件各行内容的列表
filename2 = 'pi_digits.txt'
with open(filename2) as file_object2:
#readlines()方法从文件中读取每一行,并将其存储在一个列表中。接下来该列表被存储到变量lines中
lines = file_object2.readlines()
pi_string = ''
pi_string2 = ''
for line in lines:
pi_string += line.rstrip()
#利用strip()方法删除每行左边的空格
pi_string2 += line.strip()
print(pi_string,'\n'+pi_string2)
print(len(pi_string),len(pi_string2))
#写入文件
filename = 'programming.txt'
#读取模式'r',写入模式'w',附加模式'a',读取和写入模式'r+'。如果省略模式实参,将默认以只读模式打开
#如果要写入的文件不存在,函数open将自动创建它
with open(filename,'w') as file_object:
#python只能将字符串写入文本文件中,如果要存储数值到文件中,需要用str()函数进行转换
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
with open(filename,'a') as file_object:
file_object.write("I also love find meaning in large datasets.\n")
1635



被折叠的 条评论
为什么被折叠?



