鱼C论坛

 找回密码
 立即注册
查看: 1508|回复: 4

为何open打开.py文件后不可阅读

[复制链接]
发表于 2019-5-29 23:24:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
目的是统计一个文件夹各个文件的数目和.py文件中的总行数,可是有如下错误,一直不能更改,问是何原因
import os
import easygui as g
import os.path

def searchfor():
    count_py=0
    f_py=0
    count_txt=0
    f_txt=0
    count_docx=0
    f_docx=0
    os.chdir(g.diropenbox())
    files=os.walk(os.getcwd())
    for file_aggregate in files:
        for i in file_aggregate[2]:
            
            (f_start,f_end)=os.path.splitext(i)
            if f_end=='.py':
                f_py+=1
                file_name=file_aggregate[0]+'\\'+i
                print(file_name)
               
                f=open(file_name)

                for j in list(f):
                    count_py+=1
                f.close()
            elif f_end=='.txt':
                f_txt+=1
                file_name=file_aggregate[0]+'\\'+i
                f=open(file_name,)
                for j in list(f):
                    count_txt+=1
                f.close()
            elif f_end=='.docx':
                f_docx+=1
                file_name=file_aggregate[0]+'\\'+i
                f=open(file_name+'\\'+i)
                for j in list(f):
                    count_docx+=1
                f.close()
    count_py1=count_py/100
    rest=10000-count_py
    msg='您目前共累计编写了%d行代码,完成进度:%d\n离10万行代码还差%d行,请继续努力!' % (count_py,count_py1,rest)
    tile='代码总计'
    word='【.py】源文件%d个,源代码%d行\n【.txt】源文件%d个,源代码%d行\n【.docx】源文件%d个,源代码%d行' % (f_py,count_py,f_txt,count_txt,f_docx,count_docx)
    g.textbox(msg,tile,word)
                    
searchfor()            
            

TIM图片20190529232344.png
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-5-29 23:37:14 | 显示全部楼层

回帖奖励 +1 鱼币

编码错误
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-5-29 23:47:46 | 显示全部楼层
  1. cchardet 比chardet准确度高,速度快

  2. cchardet.detect()返回字典,其中confidence是检测精确度,encoding是编码形式



  3. 1:网页编码判断:
  4. import requests
  5. import cchardet

  6. res = requests.get('http://www.baidu.com/')
  7. rawdata  = res.content
  8. cchardet.detect(rawdata)

  9. >>>{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}



  10. 2:文件编码判断

  11. import cchardet

  12. with open('c:\\111.txt','rb') as f:
  13.         msg=f.read()

  14. enc = cchardet.detect(msg)
  15. enc = enc['encoding']
  16. print(enc)



  17. # 以指定编码打开文件
  18. with open("新建文本文档.txt", "r", encoding=enc) as f:
  19.     print(f.read())


复制代码

-------------------------------------------------------------------------------------------------------------------------------------------
  1. import easygui as g
  2. import os, cchardet


  3. def get_file_code(path):
  4.     with open(path,'rb') as f:
  5.             msg=f.read()

  6.     enc = cchardet.detect(msg)
  7.     enc = enc['encoding']
  8.     return enc

  9. def show_result(start_dir):
  10.     lines = 0
  11.     total = 0
  12.     text = ""
  13.     for i in source_list:
  14.         lines = source_list[i]
  15.         total += lines
  16.         text += "【%s】源文件 %d 个,源代码 %d 行\n" % (i, file_list[i], lines)
  17.     title = '统计结果'
  18.     msg = '您目前共累积编写了 %d 行代码,完成进度:%.2f %%\n离 10 万行代码还差 %d 行,请继续努力!' % (total, total/1000, 100000-total)
  19.     g.textbox(msg, title, text)

  20. def calc_code(file_name):
  21.     lines = 0
  22.     enc = get_file_code(file_name) # 获取文件编码
  23.     with open(file_name, "r", encoding=enc) as f: # 以指定编码打开文件
  24.         print('正在分析文件:%s ...' % file_name)
  25.         try:
  26.             for each_line in f:
  27.                 lines += 1
  28.         except UnicodeDecodeError:
  29.             pass # 不可避免会遇到格式不兼容的文件,这里忽略掉......
  30.         
  31.     return lines

  32. def search_file(start_dir) :
  33.     #首先通过异常判断该文件夹是否有访问权限,这里用 os.listdir列目录尝试。
  34.     try:        
  35.         os.listdir(start_dir)
  36.     except:            
  37.         return
  38.    
  39.     os.chdir(start_dir)
  40.    
  41.     for each_file in os.listdir(os.curdir) :
  42.         ext = os.path.splitext(each_file)[1]
  43.         if ext in target :
  44.             lines = calc_code(each_file) # 统计行数
  45.             # 还记得异常的用法吗?如果字典中不存,抛出 KeyError,则添加字典键
  46.             # 统计文件数
  47.             try:
  48.                 file_list[ext] += 1
  49.             except KeyError:
  50.                 file_list[ext] = 1
  51.             # 统计源代码行数
  52.             try:
  53.                 source_list[ext] += lines
  54.             except KeyError:
  55.                 source_list[ext] = lines
  56.             
  57.         if os.path.isdir(each_file):
  58.             search_file(each_file) # 递归调用               
  59.             os.chdir(os.pardir) # 递归调用后切记返回上一层目录
  60.             
  61. target = ['.c', '.cpp', '.py', '.cc', '.java', '.pas', '.asm']
  62. file_list = {}
  63. source_list = {}

  64. g.msgbox("请打开您存放所有代码的文件夹......", "统计代码量")
  65. path = g.diropenbox("请选择您的代码库:")

  66. search_file(path)
  67. show_result(path)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-5-30 01:13:46 | 显示全部楼层

回帖奖励 +1 鱼币

中文编码的问题吧,
f=open(file_name)
这里如果改成with open(file_name,"r",encoding="utf8") as f:
你试下OK不,
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2019-5-30 09:58:54 | 显示全部楼层
yh6788 发表于 2019-5-30 01:13
中文编码的问题吧,
f=open(file_name)
这里如果改成with open(file_name,"r",encoding="utf8") as f:

感谢
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-16 03:26

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表