zoukankan      html  css  js  c++  java
  • python进行文件读写

    python进行文件读写

    1. 打开文件的两种方式

    方法一

    f = open('data.txt','r') # 获得文件对象
    f.close() # 关闭文件
    

    方法二

    with open('data.txt','r') as f:
    	str = f.read() # 对文件的操作
    

    2. 读文件

    2.1 将文件读入到一行字符串中

    str = f.read()
    

    2.2 按行读取文件

    lines = f.readlines()
    for line in lines:
    

    2.3 将文件读入到数组中

    import numpy as np
    data = np.loadtxt('data.txt')
    

    3. 写文件

    3.1 将字符串写入文件

    with open('data.txt','w') as f:
        f.write(line)
    

    3.2 列表写入文件

    data = ['a','b','c']
    with open("data.txt","w") as f:
        f.writelines(data)
    

    3.3 数组写入文件

    import numpy as np
    np.savetxt('data.txt',data) # 或 np.save('data.txt',data)
    
    ---- suffer now and live the rest of your life as a champion ----
  • 相关阅读:
    centos7上安装JupyterHub
    我的测试第一篇博客
    TCP,SYN,FIN扫描
    nmap使用帮助翻译
    MySQL 常用函数
    MySQL 视图
    MySQL 索引
    JAVA 注解
    JAVA 反射
    spring boot MySQL极简封装
  • 原文地址:https://www.cnblogs.com/popodynasty/p/14476615.html
Copyright © 2011-2022 走看看