[英]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.