繁体   English   中英

Python 错误“OSError:[Errno 22] 无效参数”

[英]Python error "OSError: [Errno 22] Invalid argument"

我发现这个 function 允许我从文件中删除最后一个字符:

def removelast(myfile):
    with open(myfile, 'rb+') as filehandle:
        filehandle.seek(-1, os.SEEK_END)
        filehandle.truncate()

当我单独测试它时它正在工作哦一个文件。 但是当我在我的程序中使用它时,我不知道为什么它会给我这个错误“OSError: [Errno 22] Invalid argument”。

这是我的程序:

import os
def removelast(myfile):
    with open(myfile, 'rb+') as filehandle:
        filehandle.seek(-1, os.SEEK_END)
        filehandle.truncate()
grades = {'Mathématiques': '20.0', 'Français': '20.0', 'ALE': '20.0', 'Espagnole': '20.0', 'Anglais': '20.0', 'SVT': '20.0', 'SPC': '20.0', 'Technologie': '20.0', 'HGPF': '20.0', 'EMC': '20.0', 'EPS': '20.0', 'Art': '20.0'}
coef = {'Mathématiques': '4', 'Français': '4', 'ALE': '1', 'Espagnole': '1', 'Anglais': '2', 'SVT': '2', 'SPC': '2', 'Technologie': '1', 'HGPF': '2', 'EMC': '1', 'EPS': '1', 'Art': '1'}
def foo(l):
    return list(map(float, l))

Complete_name2 = "D:/Users/Jean Paul/OneDrive/Programming/Programs/Prog 2 - Moyenne de Notes/recalculating.py"

f = open(Complete_name2, "w+")
gradev = foo(list(grades.values()))
coefv = foo(list(coef.values()))
r = 0
a = 0
while r < len(foo(list(grades.values()))):
    print("calculation" + str(r) + " = " + "(" + str(gradev[a]) + " * " + str(coefv[a]) + ")", file = f)
    r = r + 1
    a = a + 1

这是不起作用的部分(我试图在文件末尾打印"str(eval(<first variables that has been created earlier> + <second> + <third> +...)) ) :

print("")
myprint = "average_p1 = eval("
r2 = 0
while r2 < r:
    myprint = myprint + "calculation" + str(r2) + "+"
    r2 = r2 + 1
removelast(Complete_name2)

recalculating.py已创建:

calculation0 = (20.0 * 4.0)
calculation1 = (20.0 * 4.0)
calculation2 = (20.0 * 1.0)
calculation3 = (20.0 * 1.0)
calculation4 = (20.0 * 2.0)
calculation5 = (20.0 * 2.0)
calculation6 = (20.0 * 2.0)
calculation7 = (20.0 * 1.0)
calculation8 = (20.0 * 2.0)
calculation9 = (20.0 * 1.0)
calculation10 = (20.0 * 1.0)
calculation11 = (20.0 * 1.0)

Output:

Traceback (most recent call last):
  File "d:\Users\Jean Paul\OneDrive\Programming\tests python\test3.py", line 29, in <module>
    removelast(Complete_name2)
  File "d:\Users\Jean Paul\OneDrive\Programming\tests python\test3.py", line 4, in removelast
    filehandle.seek(-1, os.SEEK_END)
OSError: [Errno 22] Invalid argument

当您输入错误或无效的文件路径时,通常会出现此错误。 检查你的文件路径 -

在文件路径前添加 r。 这可能有帮助 - 前导 r 表示 python 原始字符串。 它将 \ 视为文字字符。

在文件路径前添加 r 使其类似于 - open(r"C:\folder\yourfile.txt","r")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM