• 操作文件1


    with open('readerFile.txt') as file_object:
        contents = file_object.read()
        print(contents)
      file_object.close()

    要现在这个你书写的.py的文件夹里去添加一个readFile.txt文件,注意这个文件夹里不能添加汉字,open(参数1),这个函数是打开一个参数1的文件,这个参数1是文件的名字

    open()函数会返回这个文件的一个对象,可以使用as 后加一个名字,例如这个上的file_object就是这个文件的一个对象。当然.close(就是关闭一个文件).read就是来读取这个文件的全部内容放到字符串contents中。然而这个read函数读取到最后一行的时候回事空的一行在直接打印contents的时候会有多一行的空行,需要这么来写可以省去空行。

    with open('readerFile.txt') as file_object:
        contents = file_object.read()
        print(contents.rstrip())
        file_object.close()

    当你存放文件的路径不在这文件夹里的时候,你就需要传入一个精确地文件路径。

    方法有两个:

    #1
    with open('E:/python/day5/filePath/readerFile.txt') as file_object:
       contents = file_object.read()
       print(contents.rstrip())
       file_object.close()
    
    #2
    path = 'E:/python/day5/filePath/readerFile.txt'
    with open(path) as file_object:
       contents = file_object.read()
       print(contents.rstrip())
       file_object.close()

    有时候我们需要一行一行的拿出数据来打印,我们可以使用for循环来实现

    path = 'E:/python/day5/filePath/readerFile.txt'
    with open(path) as file_object:
      for line in file_object:
        print(line,end="")
    path = 'E:/python/day5/filePath/readerFile.txt'
    with open(path) as file_object:
      for line in file_object:
        print(line.rstrip())

    使用关键字with时,open()返回的文件对象只能在with语句块中使用,只要是出了with语句块这个文件对象就会失效,所以我们可以使用一个列表,这样在with体外也就能使用了,其中用到了readlines()这个方法,他会把每一行存放到一个列表中,在使用lines把这个列表接过来,这样lines也就是一个列表了

    path = 'E:/python/day5/filePath/readerFile.txt'
    with open(path) as file_object:
        lines = file_object.readlines()
    for line in lines :
        print(line.rstrip())

    我们有时候需要只用文件中的字符串也可以直接保存到一个字符串中,这里需要去除空格,我们用的时候strip()而不是rstrip().

    path = 'E:/python/day5/filePath/readerFile.txt'
    with open(path) as file_object:
        lines = file_object.readlines()
    pi_string = ''
    for line in lines :
        pi_string += line.strip()
    print(pi_string)

    我们也可以只打印ip_string中的前几个字符:

    print(pi_string[:7] + "......")  #abcdefg......

    #文件的写入

    使用到了open(参数1,参数2),参数1还是文件路径名,参数2是 ‘r’ , 'w' , 'a', 'r+'。‘r’只读,‘w’是写入,‘a’是在原有的文件夹里最后的位置追加内容,‘r+’是读取和写入文件模式

    如果使用‘w’的话,千万小心,因为当这个文件夹里存在这个文件了的话。他会把这个文件清空,在写入数据。

    #给文件写入数据
    with open('write_file.txt','w') as file_object:
        file_object.write('this is my first write_file
    ')

    我们有时候可以把可能出现异常的代码放在try语句中,如果真的出现错误了,就会执行except内的语句块:其中ZeroDivisionError是关键字

    try:
        print(5/0)
    except ZeroDivisionError:
        print("Zero can't be divide")
  • 相关阅读:
    bzoj 1040: [ZJOI2008]骑士
    CF Playrix Codescapes Cup Problems Analysis
    C++ 指针[转+原创]
    高斯消元
    NOIP模拟
    线段树合并
    After ZJOI2017 day2
    ZJOI 2017 day2 4.27
    ZJOI 2017 二试 day1 4.26
    ZJOI 2017 二试 day0
  • 原文地址:https://www.cnblogs.com/boost/p/13409877.html
Copyright © 2020-2023  润新知