Python笔记-014-文件和异常

1.14.1 用文件路径打开文件
通过绝对路径,可以读取系统任何地方得文件。就目前而言,最简单得做法,要么将数据文件存储再程序文件所在得目录,要么将其存储再程序文件所在目录下得一个文件夹(如text_files)中

pi_digits.txt

3.141592653589793238462643383279

1.14.2 使用文件的内容
将文件读取到内存中后,将可以以任何方式使用这些数据了。

file_path='E:\Python_Study\python_charm\pi_digits.txt'
with open(file_path) as file_object:
     contents= file_object.read()

3.141592653589793238462643383279


file_path='E:\Python_Study\python_charm\pi_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()
pi_string=''
for line in lines:
    pi_string +=line.rstrip()

print(pi_string)
print(len(pi_string))

3.1415926535 8979323846 2643383279
36

1.14.3 写入空文件

file_path='pi_digits.txt'
with open(file_path,'w') as file_object:
    file_object.write("I love programing.\n")
    file_object.write("I love creating new games.\n")
with open(file_path) as file_object:
    lines = file_object.readlines()
pi_string=''
for line in lines:
    pi_string +=line
print(pi_string)

I love programing.
I love creating new games.

第二行加入with open 的原因我也不知道这样对不对,到目前位置,我只能这样先处理,等后面学到再更新。

1.14.4 写入多行

file_path='pi_digits.txt'
with open(file_path,'a') as file_object:
    file_object.write("I also love finding meaning in large datasets.\n")
    file_object.write("I  love creating apps that can run in a browser..\n")
with open(file_path) as file_object:
    lines = file_object.readlines()
pi_string=''
for line in lines:
    pi_string +=line
print(pi_string)

I love programing.
I love creating new games.
I also love finding meaning in large datasets.
I love creating apps that can run in a browser..

动手练一练
10-1 10-2

while True:
        print("Enter 'quit' to Stop it ")
        names=input("Please tell me your name:")
        if  names=='quit':
            break
            file.close()
        else:
            file_path='pythontest.txt'
            with open(file_path,'a') as file_object:
                file_object.write(names.title()+'\n')
            with open(file_path) as file_object:
                lines = file_object.readlines()
            name_string=''
            for name in names:
                name_string+=name
            print(name_string+",Nice to meet you!")

10-5

filename='pythontest.txt'
responses=[]
while True:
    response= input("\n Why do you like Programing?")
    responses.append(response)

     """这一部分是在网上学习来的,觉得这种询问的写法挺适合我的 添加进来,学习学习"""
    continue_poll =input("Would you like to let someone else respond?(y/n)")     
    if continue_poll != 'y':      
        break
with open(filename,'a') as f:
    for response in responses:
        f.write(response+"\n")

1.14.5 存储数据
很多程序都要求用户输入某种信息这里写代码片

猜你喜欢

转载自blog.csdn.net/qq_35989861/article/details/82291858