PYTHON教程之用户输入文件操作

51changxuePython评论187 views阅读模式

PYTHON教程之用户输入文件操作

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

 

继续阅读
51changxue
  • 本文由 发表于 2018年4月6日 12:30:42
  • 转载请务必保留本文链接:https://51changxue.com/412.html
pycharm永久破解激活教程 Python

pycharm永久破解激活教程

PyCharm是一种Python IDE,带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如调试、语法高亮、Project管理、代码跳转、智能提示、自动完成、...
Tkinter控件快速引用总结 Python

Tkinter控件快速引用总结

  文件名称: Tkinter控件快速引用总结代码.rar 文件大小: 4k 更新日期: 2018-7-29 文件版本: V1.0 免责声明: 本站大部分下载资源收集于网络,只做学习和交流使...
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定