写入空文件
filenametxt='test1.txt'with open(filenametxt,'w') as file_object: file_object.write("hello world")
第一行:我们定义了一个txt文件,命名为test1.txt,并把这个文件赋值给filenametxt
第二行:我们使用with open()方法打开文件,并使用'w' ,代表写入文件
第三行:使用write()方法将 ”hello world “写入文件
这个程序没有输出结果,我们可以看看创建的txt文件:
我们使用程序创建,并写入了”Hello world “. 我们总结一下open()方法的几种模式:
- ”r“ , 只读模式,也是默认的模式
- ”w“ ,写入模式,允许程序对文件进行更改,需要小心,如果,原文件存在,则种方式会先清空文件,然后写入值
- ”r+“,读写模式,
- ”a“,附加模式--不改变原文件内容,在原文件基础上添加内容
写入多行文本
filenametxt='test2.txt'with open(filenametxt,'w') as file_object: file_object.write("hello world") file_object.write("hello python")
第一行:我们定义了一个txt文件,命名为test1.txt,并把这个文件赋值给filenametxt
第二行:我们使用with open()方法打开文件,并使用'w' ,代表写入文件
第三行:使用write()方法将 ”hello world “写入文件
第四行:使用write()方法将 ”hello python “写入文件
这个程序没有输出结果,我们可以看看创建的txt文件:
打印出的文本,全都被放在同一行了,这样可读性差,如何将其分行打印?前面我们提到的换行符,就可以做到:
filenametxt='test2.txt'with open(filenametxt,'w') as file_object: file_object.write("hello world\n") file_object.write("hello python\n")
第一行:我们定义了一个txt文件,命名为test1.txt,并把这个文件赋值给filenametxt
第二行:我们使用with open()方法打开文件,并使用'w' ,代表写入文件
第三行:使用write()方法将 ”hello world “写入文件,并加入换行符
第四行:使用write()方法将 ”hello python “写入文件,并加入换行符
此时可以看到,我们打印的内容进行了换行。
附加内容
如果我们只想在一个已有的文本内添加入更多的数据,应该怎么操作呢?
如上文件,我们需要在第三行输出"Hello programming":4
filenametxt='test2.txt'with open(filenametxt,'a') as file_object: file_object.write("hello programming\n")
第一行:我们定义了一个txt文件,命名为test2.txt,并把这个文件赋值给filenametxt
第二行:我们使用with open()方法打开文件,并使用'a' ,代表写入文件
第三行:使用write()方法将 ”hello programming“写入到文本文件中,并不清除原有内容
结果如下:
上期答案与本期习题
上期答案:
- 创建一个包含三行三列的txt文件,读取第三列的数,并只打印第三列的数据。
with open("python_test.txt") as file_object: txt_contents=file_object.readlines() for line in txt_contents: line=line.strip() line=line.split(";") print(line[2])
执行结果: