美文网首页python
python3读写文件的方式:

python3读写文件的方式:

作者: wodeliang | 来源:发表于2017-09-05 18:30 被阅读36次

    一、读取文本格式的文件:
    open

    handle=open('C:\\User\\登亮\\Desktop\\test.csv')
    print(handle.read())
    file=open('filename','r')          #读取(默认)
    file=open('filename','w')          #写入
    

    读取内容的方式:

    file.read()                        #一次读取整个文件,不适用于太大文件
    file.readline()                    #一次只读取一行,占内存小,速度慢
    file.readlines()                   #一次性读取,将内容分成一个行的列表,可由for...in...处理
    

    写文件方式:

    filename.write()                   #不换行
    file.writelines()                  #下次会写在下一行
    close
    file.close()
    

    例:

    handle=open('C:\\User\\登亮\\Desktop\\test.csv','r')            #以读方式打开文件
    result=list()
    for line in handle.readlines():                                 #依次读取每行
        line=line.strip()                                           #去掉每行头尾空白
        if not len(line) or line.startswith('#'):                   #判断是否是空行或注释行
            continue                                                #是的话,跳过不处理
        result.append(line)                                         #保存
    result.sort()                                                   #排序结果
    handle.close()                                                  #关闭文件
    with open ('new_file.txt','w')as fw:                            #with方式不需要再进行close
        fw.write('%s' % '\n'.join(result))                          #保存入结果文件
    

    二、读取csv格式的文件:

    import pandas
    file=pd.read_csv('filename')
    

    例:

    mydata=pd.read_csv('C:\\Users\\登亮\\Desktop\\dengliang.csv')
    print(mydata)
    

    相关文章

      网友评论

        本文标题:python3读写文件的方式:

        本文链接:https://www.haomeiwen.com/subject/pnhpjxtx.html