zoukankan      html  css  js  c++  java
  • python 读取文件1

     1、脚本

    from sys import argv

    script,filename = argv

    txt = open(filename)

    print ("the filename is %s" %filename)
    print (txt.read())

    print ("Type the filename again:")
    file_again = input(">")

    txt_again = open(file_again)
    print(txt_again.read())

    2、执行结果

         

    3、备注

    00.txt和01.txt,new.py都是我桌面的文档

           

    4、读取个别文档时候,提示:UnicodeDecodeError: 'gbk' codec can't decode byte 0xa2 in position 50: illegal multibyte sequence

     使用python的时候经常会遇到文本的编码与解码问题,其中很常见的一种解码错误如题目所示,下面介绍该错误的解决方法,将‘gbk’换成‘utf-8’也适用。 
    (1)首先在打开文本的时候,设置其编码格式,如:open(‘1.txt’,encoding=’gbk’); 
    (2)若(1)不能解决,可能是文本中出现的一些特殊符号超出了gbk的编码范围,可以选择编码范围更广的‘gb18030’,如:open(‘1.txt’,encoding=’gb18030’); 
    (3)若(2)仍不能解决,说明文中出现了连‘gb18030’也无法编码的字符,可以使用‘ignore’属性进行忽略,如:open(‘1.txt’,encoding=’gb18030’,errors=‘ignore’); 
    (4)还有一种常见解决方法为open(‘1.txt’).read().decode(‘gb18030’,’ignore’)

  • 相关阅读:
    document 对象
    AdodbStream的方法和属性
    WEB开发者版本
    ATI HD2400
    驱蚊植物
    PHP5+UTF8多文件上传类
    nVIDIA_driver
    ati
    Zend_Http_Client setFileUpload
    Sqlserver2005 数据类型
  • 原文地址:https://www.cnblogs.com/merry-0131/p/8436342.html
Copyright © 2011-2022 走看看