写入文件会随机失败

2024-10-01 17:33:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个应用程序来检查新的动画情节,但我遇到了一个wierd问题。 当写入一个文件时,写操作会在随机的时间点随机地失败,但有时它会毫无问题地运行。我搞不懂这个家伙。 下面是代码的问题部分:

def write_results(results, result_dir):
    bar = progressbar.ProgressBar()
    for i in bar(range(100)):
        time.sleep(0.02)
        list = results
        for line in list:
            file = result_dir
            with open(file, "w", encoding="UTF-8") as file:
                list.sort()
                for line in list:
                    file.write('' + line + '\n')

def main():
    call(["python", "anime_app.py"])
    file_dir = r"C:/Users/username/PycharmProjects/ShowDownloader/filelist.txt"
    result_dir = r"C:/Users/username/PycharmProjects/ShowDownloader/results.txt"
    read = read_file(file_dir)
    content = get_content(read)
    site = read_site(content)
    results = write_results(site, result_dir)

错误总是一样的:

File "C:/Users/username/PycharmProjects/ShowDownloader/anime_web_app.py", line 15, in write_results
    with open(file, "w", encoding="UTF-8") as file:
OSError: [Errno 22] Invalid argument: 'C:/Users/username/PycharmProjects/ShowDownloader/results.txt'

“随机”发生的例子:

97% (97 of 100) |####################### | Elapsed Time: 0:00:03 ETA:  0:00:00Traceback (most recent call last):
  File "C:/Users/username/PycharmProjects/ShowDownloader/anime_web_app.py", line 62, in <module>
main()
  File "C:/Users/username/PycharmProjects/ShowDownloader/anime_web_app.py", line 59, in main
    results = write_results(site, result_dir)
  File "C:/Users/username/PycharmProjects/ShowDownloader/anime_web_app.py", line 15, in write_results
with open(file, "w", encoding="UTF-8") as file:
OSError: [Errno 22] Invalid argument: 'C:/Users/username/PycharmProjects/ShowDownloader/results.txt'`

Tags: inpyappdirlineusernameresultusers
2条回答

我不知道我做了什么,但清理了代码一点,删除了额外的for循环和修复progressbar和写现在是完美的工作。下面是固定代码。你知道吗

def write_results(results, result_dir):
try:
    pbar = ProgressBar()
    list = results
    write_file = result_dir
    with io.open(write_file, "w", encoding="UTF-8") as file:
        for line in pbar(list):
            time.sleep(0.1)
            list.sort()
            file.write('' + line + '\n')
except Exception:
    print("\n" + str(Exception))
    pass

def main():
loop = 0
while loop < 20:
    loop += 1
    call(["python", "anime_app.py"])
    file_dir = r"C://Users//username//PycharmProjects//ShowDownloader//filelist.txt"
    result_dir = r"C://Users//username//PycharmProjects//ShowDownloader//results.txt"
    read = read_file(file_dir)
    content = get_content(read)
    site = read_site(content)
    results = write_results(site, result_dir)

您可以这样尝试,io模块更适合于写入UTF-8文件,而codecs模块主要用于读取文件:

import io

with io.open(file, "w", encoding="UTF-8") as file:
    ...

相关问题 更多 >

    热门问题