文件操作-py

文件操作

向文件中写入字符

例:

s = str(input("please enter filename:"))
ch = str(input("please enter char:"))
f = open(s,"w")
f.write(ch)
f.close()

运行结果

 或

#-*-coding:utf-8 -*-
ch = "你好"
f = open('D:\test.txt',"w")
f.write(ch)
f.close()
运行结果

从文本文件中读取字符

例:

#-*- coding:utf-8 -*-
f = open("D:\test.txt",'r')
print(f.read()) #读取文本文件中所有字符,read(5)表示读取文本文件中的前5个字符
f.close()

运行结果

原文地址:https://www.cnblogs.com/2277098974-qqcom/p/8561197.html