【问题标题】:Json Script Won't Properly RunJson 脚本无法正常运行
【发布时间】:2021-12-11 21:21:53
【问题描述】:

所以我正在编写一个脚本来获取一个 .txt 文件并

  1. 附加每行的字符串表示
  2. 在文档的开头和结尾附加一个字符串。

所以

你好,

我叫 Jim,很高兴能开始为 Microsoft 工作。一世 相信我的工作经历完全符合微软文化。

谢谢!吉姆

会变成

大家好,\n 我叫 Jim,很高兴能开始为 Microsoft 工作。我相信我的工作经历完全符合微软文化。 \n谢谢! \n吉姆

同时在开头附上以下内容

{"prompt":"", "completion":"

最后是以下内容

"}

现在我有以下脚本,它成功占用最多 2 个 .txt 并创建字符串表示并在前端和末尾附加所需的键,但它不能做超过 2 个 PLUS 得到以下错误

PermissionError: [Errno 13] Permission denied

脚本

import sys
import os
import json
import os


if len(sys.argv) != 2:
    print("Please add a directory")
    sys.exit(0)

directory = sys.argv[1]

new_dir = os.path.abspath(directory+"/script_output")

if not os.path.isdir(new_dir):
    os.mkdir(new_dir)

for f_str in os.listdir(directory):

    if os.path.isdir(os.path.abspath(directory+f_str)):
        continue

    json_data = {}
    json_data["prompt"] = ""
    f_abs = os.path.abspath(os.path.join(directory, f_str))

    og_file = new_dir + "/" + f_str
    json_file = new_dir + "/" + os.path.splitext(f_str)[0] + ".json"

    f = open(f_abs, "r", encoding="utf-8")
    new_txt = repr(f.read())[1:-1]
    json_data["completion"] = new_txt

    with open(json_file, "w") as output_file:
        json.dump(json_data, output_file)

print("Done")

编辑 1:

如您所见,我有 2 个文本文件应该在 script_output 文件夹中转换为 Json 文件。当我运行注释代码时,没有错误,但文件没有出现。

【问题讨论】:

  • 完成,谢谢。
  • 显然是文件权限问题。您可以通过简单地尝试打开文件并查看其工作原理来解决问题;其余的都无关紧要。
  • 始终将完整的错误消息(从单词“Traceback”开始)作为文本(不是屏幕截图,不是指向外部门户的链接)(不是在 cmets 中)。还有其他有用的信息。
  • 错误可能提示您使用open() 中的目录。也许先检查一下f_abs 中的内容。
  • 你的大错误是directory+f_str 创建了错误的路径directoryfilename 而不是directory/filename - 并且isdir() 给出了False。您应该使用directory + "/" + f_str 或更好地使用os.path.join(directory, f_str)

标签: python file web-scraping


【解决方案1】:

问题很清楚。

运行脚本的上下文中的用户没有文件的读取权限:C:\Users\Antonio\Desktop\Rank\script_output

它是作为批处理作业运行的,所以是不同的用户吗?

另一个问题可能与此有关。打开该文件后,您没有关闭该文件。你正在循环打开输入文件。

另外这条线应该做什么?因为它什么都不做

if os.path.isdir(os.path.abspath(directory+f_str)):
    continue

有人注意到您对输出文件使用了上下文管理器:

with open(json_file, "w") as output_file:

同样你应该使用

with open(f_abs, 'r', encoding="utf-8") as input_file:

【讨论】:

    【解决方案2】:

    我认为问题在于您没有使用正确的目录来加载文件。我假设您要加载存储在 /script_output/ 文件夹中的文件 2.txt(类似的东西)。

    尝试从你有script_output文件夹的地方运行文件并像python stack.py .一样运行,我使用.作为当前目录并将我的脚本命名为stack.py来举例说明。

    请尝试使用以下脚本:

    import sys
    import os
    import json
    import os
    
    
    if len(sys.argv) != 2:
        print("Please add a directory")
        sys.exit(0)
    
    directory = sys.argv[1]
    
    new_dir = os.path.abspath(directory+"/script_output")
    
    if not os.path.isdir(new_dir):
        os.mkdir(new_dir)
    
    for f_str in os.listdir(new_dir):
        if os.path.isdir(os.path.abspath(new_dir+f_str)):
            continue
    
        json_data = {}
        json_data["prompt"] = ""
        f_abs = os.path.abspath(os.path.join(new_dir, f_str))
    
        og_file = new_dir + "/" + f_str
        json_file = new_dir + "/" + os.path.splitext(f_str)[0] + ".json"
    
        f = open(f_abs, "r", encoding="utf-8")
        f = open(f_abs, "r")
        new_txt = repr(f.read())[1:-1]
        json_data["completion"] = new_txt
    
        with open(json_file, "w") as output_file:
            json.dump(json_data, output_file)
    

    【讨论】:

    • 感谢您的回复!因此文件运行,但不再生成输出。 “Script_output”文件夹应该获取目录中的文件,并在文件夹中输出新的 json 版本。见编辑 1
    • 该文件将在script_output/ 中生成,我编写的代码使得输入文件也需要存在于script_output/
    【解决方案3】:

    我无法对其进行测试,但对我来说,所有问题都是您使用 + 而不是 os.path.join() 创建路径

    当您检查 isdir() 时,您使用 directory+f_str 创建字符串 directoryscript_output 而不是 directory/script_output 然后 isdir() 返回 False 稍后它会尝试运行 open("directory/script_output") - 所以它会尝试打开目录 -这给了你的错误。

    如果你使用os.path.join(),你就不会遇到这个问题


    我的版本(有其他更改):

    我还检查了扩展名.txt 以确保我读取了正确的文件。

    我使用更具可读性的变量。

    import os
    import sys
    import json
    
    #directory = sys.argv[1]
    directory = "test"
    
    input_dir  = os.path.abspath(directory)  # later I will no need `abspath()`
    output_dir = os.path.join(input_dir, "script_output")
    
    os.makedirs(output_dir, exist_ok=True)  # doesn't need `if`
    
    for name in os.listdir(input_dir):
        input_path = os.path.join(input_dir, name)
        #print('input_path:', input_path)
        
        if os.path.isdir(input_path):
            print('dir:', input_path) 
            continue
    
        basename, ext = os.path.splitext(name)
    
        if ext != '.txt':
            print('wrong ext:', input_path)
            continue
    
        print('>>> processing:', input_path)
        
        json_data = {}
        json_data["prompt"] = ""
        
        json_file = os.path.join(output_dir, basename + ".json")
    
        with open(input_path, "r", encoding="utf-8") as f:
            json_data["completion"] = f.read()[1:-1]
    
        with open(json_file, "w", encoding="utf-8") as f:
            json.dump(json_data, f)
    
    print("Done")
    

    【讨论】:

    • 成功了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 2012-07-15
    相关资源
    最近更新 更多