zoukankan      html  css  js  c++  java
  • 文件的基本处理

    打开文件-->文件操作-->关闭文件

     

    打开文件 

    Open() 

    <variable> = open (<name>, <mode>) 

    <name>磁盘文件名 

    <mode>打开模式 (r, w, a, rb, wb, ab, r+)

    例如:

      >>> infile = open (“numbers.dat”, “r”) 

      >>> infile = open (“music.mp3”, “rb”) 

     

    文件读取 

    read() 返回值为包含整个文件内容的一个字符串 

    readline() 返回值为文件下一行内容的字符串。 

    readlines() 返回值为整个文件内容的列表,每项是以换行符为结尾的一行字符串。 

     

    写入文件 

    从计算机内存向文件写入数据 

    write():把含有本文数据或二进制数据块的字符串写入文件中。 

    writelines():针对列表操作,接受一个字符串列表作为参数,将它们写入文件。 

     

    文件遍历 

    最常见的文件处理方法 

    举例 

    拷贝文件 

    根据数据文件定义行走路径 

    将文件由一种编码转换为另外一种编码 

     

    遍历文件模板 

    通用代码框架: 

    1 file = open (someFile, "r") 
    2 
    3 For line in file.readlines(): 
    4 
    5   #处理一行文件内容 
    6 
    7 file.close() 

    简化代码框架: 

    1 file = open (someFile, "r") 
    2 
    3 For line in file: 
    4 
    5   #处理一行文件内容 
    6 
    7 file.close() 

     

    举例:文件拷贝 

     1 def main():
     2     # 用户输入文件名
     3     f1 = input("Enter a source file:").strip()
     4     f2 = input("Enter a destination file:").strip()
     5 
     6     # 打开文件
     7     infile = open(f1, "r")
     8     outfile = open(f2, "w")
     9 
    10     # 拷贝数据
    11     countLines = countChars = 0
    12     for line in infile:
    13         countLines += 1
    14         countChars += len(line)
    15         outfile.write(line)
    16     print(countLines, "lines and", countChars, "chars copied")
    17 
    18     # 关闭文件
    19     infile.close()
    20     outfile.close()
    21 
    22 main()

     

     

     

     

  • 相关阅读:
    JAVA基础——编程练习(二)
    JAVA基础——面向对象三大特性:封装、继承、多态
    JVM内存
    50. Pow(x, n) (JAVA)
    47. Permutations II (JAVA)
    46. Permutations (JAVA)
    45. Jump Game II (JAVA)
    43. Multiply Strings (JAVA)
    42. Trapping Rain Water (JAVA)
    41. First Missing Positive (JAVA)
  • 原文地址:https://www.cnblogs.com/aze-003/p/5128040.html
Copyright © 2011-2022 走看看