PYTHON教程之用户输入文件操作
#1.函数input()让程序暂停运行,等待用户输入一些文本并赋值给变量
a_input=input('please input a number:')
print('this number is:',a_input)
#将输入的文本变成数字,int(a_input)
if int(a_input)>18:# 如果直接使用a_input则会报错'>' not supported between instances of 'str' and 'int'
print(a_input)
#2.用open函数打开文件
my_file=open('my file.txt','r') #用法: open('文件名','形式'), 其中形式有'w':write;'r':read.a:'append'
mytext=my_file.read()#使用 file.read() 能够读取到文本的所有内容
print(mytext)
my_file.close()
#关闭文件
#按行读取 file.readline()
my_file=open('my file.txt','r')
mytext2=my_file.readline()
mytext3=my_file.readline()
print(mytext2)
print(mytext3)
my_file.close()
#读取所有行 file.readlines(),如果想要读取所有行, 并可以使用像 for 一样的迭代器迭代这些行结果,
# 我们可以使用 file.readlines(), 将每一行的结果存储在 list 中, 方便以后迭代.
my_file=open('my file.txt','r')
mytext4=my_file.readlines()
print(mytext4)
my_file.close()
for item in mytext4:#逐行输出
print(item)
#写入文件,write()是删除重写,即光标从最开始位置启动,之后跟着光标走,append方式打开再write从文本内容结束位置启动
textchange='我爱我家,\n我爱我的家人,\n是的,\n就是这样的,\nverygood'
my_file=open('my file.txt','w')
my_file.write(textchange)
my_file.close()
my_file=open('my file.txt','r')
mytext=my_file.read()
print(mytext)
my_file.close()
texappend='\n哎呦,不错呀'
my_file=open('my file.txt','a')
my_file.write(texappend)
my_file.write('\n再增加一句!')
print(mytext)
my_file.close()
my_file=open('my file.txt','r')
mytext=my_file.read()
print(mytext)
my_file.close()
运行结果:
"D:\Program Files\python\python.exe" "D:/Program Files/python/example/PYTHON教程之用户输入文件操作.py" please input a number:50 this number is: 50 50 我爱我家, 我爱我的家人, 是的, 就是这样的, verygood 哎呦,不错呀 我爱我家, 我爱我的家人, ['我爱我家,\n', '我爱我的家人,\n', '是的,\n', '就是这样的,\n', 'verygood\n', '哎呦,不错呀'] 我爱我家, 我爱我的家人, 是的, 就是这样的, verygood 哎呦,不错呀 我爱我家, 我爱我的家人, 是的, 就是这样的, verygood 我爱我家, 我爱我的家人, 是的, 就是这样的, verygood 我爱我家, 我爱我的家人, 是的, 就是这样的, verygood 哎呦,不错呀 再增加一句! Process finished with exit code 0


评论