小星圆55 2022-03-26 17:15 采纳率: 33.3%
浏览 393

打开文件时,就像看不到文件,FileNotFoundError: [Errno 2] No such file or directory: 'setting.json'

问题遇到的现象和发生背景

编写字符画,想打开一个设置的json文件。文件有了,用open()打开时它说没有该文件。

问题相关代码,请勿粘贴截图
from PIL import Image
import json


class Img(Image.Image):
    def __init__(self, img: Image.Image):
        self.img = img.convert('L')

    def get_img(self):
        return self.img

    @staticmethod
    def getchar(gray, ls=list('W#C)|^. ')):
        print(len(ls))
        if 65536 % len(ls) != 0:
            raise ValueError('Input data must divide 65536 (that is, a multiple of 4)')
        return ls[int(gray // (256 // len(ls)))]


class write_file(object):
    def __init__(self, filename, text, mode='w', ):
        self.file = open(filename, mode)
        self.file.write(text)
        try:
            self.close()
        except:
            pass

    def close(self):
        self.file.close()


def main(img_name='exp.jpg'):
    setting_file = open('setting.json', 'r')
    setting = json.load(setting_file)
    t = 0.2
    img = Image.open(img_name)
    img = Img(img).get_img().resize((round(img.width*t), round(img.height*t)))
    text = ''
    for y in range(img.height):
        for x in range(img.width):
            text += Img.getchar(img.getpixel((x, y)))
        text += '\n'
    fo = write_file('ZiFuHua.txt', text)


运行结果及报错内容
Traceback (most recent call last):
  File "D:\py_proj\XingYuan\字符画\字符画.py", line 62, in <module>
    main()
  File "D:\py_proj\XingYuan\字符画\字符画.py", line 34, in main
    setting_file = open('setting.json', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'setting.json'

img

我想要达到的结果

它咋就看不着那个文件呢??

  • 写回答

1条回答 默认 最新

  • 陈年椰子 2022-03-26 17:26
    关注

    程序缺省目录的问题?
    把这两句加到main里,
    看看程序目录

    import os
    print(os.getcwd())
    
    
    评论

报告相同问题?

问题事件

  • 创建了问题 3月26日

悬赏问题

  • ¥15 flutter网页应用用python的http服务器访问速度慢
  • ¥15 VESTA绘图原子颜色显示异常
  • ¥15 天翼云搭建多ip l2tp
  • ¥15 python实现CAD识图
  • ¥15 如何实现在renpy中创建并应用不同大小尺寸对话框?
  • ¥15 table表格有一列是固定列 滑动到最下面时 固定的那一列有几行没显示出来
  • ¥20 单细胞数据注释时报错
  • ¥15 vscode编译ros找不到头文件,cmake.list文件出问题,如何解决?(语言-c++|操作系统-linux)
  • ¥15 通过AT指令控制esp8266发送信息
  • ¥15 有哪些AI工具提供可以通过代码上传EXCEL文件的API接口,并反馈分析结果