python练习使用文件的读写,和定义函数
题目:
编写一个程序,它允许用户在文件的文本中导航。程序提示用户输入一个文件名,并且输入想要放入到列表中的文本行。然后,程序进入到循环当中,他会输出文件的行数,并且提示用户输入一个行号。实际的行号范围是从1到文件中的行数。如果用户输入0,程序退出。否则,程序输出和该行号相关的行。
思路
定义两个主函数,一个用于交互,另外一个用于读写文件。
读写文件
这里没有使用whlle循环。其实while进行循环更好。
def read(name,texts = "",path = 'D:\gongyong\alibaba'):
paths = os.path.join(path,name)
f = open(paths,'a')
if texts == "":
text = ""
else:
text = "\n" + texts
f.write(text)
f.close()
f = open(paths,'r')
txt = f.read()
line_list = txt.splitlines()
count = len(line_list)
def inputs():
get_line = int(input("查看哪一行:"))
return get_line
def check(get_line):
if get_line > 0:
if get_line < count+1:
get_line_text = line_list[get_line-1]
print(get_line_text)
print("if you want exit, please input 0.")
check(inputs())
else:
print("You number is out of range, please input another.")
check(inputs())
else:
exit()
check(inputs())
f = open(paths,‘a’)追加写入。其实用 ‘a+’ 也可以打开文件,但是如果不close文件是无法读取到新写入的一行的,亲测,原因未找到。所以先close()保存再打开读取。
交互
def exchange():
line = input("文件名:")
line2 = input("文件路径:")
text = input("输入的文本:")
if len(line2) == 0:
s = read(line,text,line2)
else:
s = read(line,text)
return s
全部代码
import os
def read(name,texts = "",path = 'D:\alibaba'):
paths = os.path.join(path,name)
f = open(paths,'a')
if texts == "":
text = ""
else:
text = "\n" + texts
f.write(text)
f.close()
f = open(paths,'r')
txt = f.read()
line_list = txt.splitlines()
count = len(line_list)
def inputs():
get_line = int(input("查看哪一行:"))
return get_line
def check(get_line):
if get_line > 0:
if get_line < count+1:
get_line_text = line_list[get_line-1]
print(get_line_text)
print("if you want exit, please input 0.")
check(inputs())
else:
print("You number is out of range, please input another.")
check(inputs())
else:
exit()
check(inputs())
def exchange():
line = input("文件名:")
line2 = input("文件路径:")
text = input("输入的文本:")
if len(line2) == 0:
s = read(line,text,line2)
else:
s = read(line,text)
return s
测试
exchange()
测试结果
文件名:text
文件路径:
输入的文本:ce shi jie guo
查看哪一行:1
wo xiang chi rou
if you want exit, please input 0.
查看哪一行:11
You number is out of range, please input another.
查看哪一行:12
You number is out of range, please input another.
查看哪一行:10
ce shi jie guo
if you want exit, please input 0.
查看哪一行:0
Process finished with exit code 0
文本不输入就是默认不输入文本行,路径不输入就是默认路径。