|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
错误代码:
#books//news.py
import time
import os
def news(*name, paths="books//Python_book", order='file'):
def calc_time():
f_time = ""
t = time.localtime()
dw = ["年", "月", "日", "时", "分", "秒"]
i = 0
for index in t:
f_time.join(index + dw[i])
i += 1
return f_time
def news_file(*name, path):
for each in name:
if os.path.isfile(str(path).join(str(each))):
print(str(each).join("已存在!"))
else:
with open("w", str(path.join(str(each)))) as f:
f.write(clac_time())
def news_dir(*name, path):
if os.isdir(str(path).join(str(each))):
print(str(each).join("已存在!"))
else:
os.mkdir(str(path).join(str(each)))
with open("w", str(path).join(str(each)).join("创建日期")) as f:
f.write(clac_time())
def news_python_book(number):
with open("books//number", "+") as f1:
n = int(f1.read())
for index in range(number1):
with open("books//Python_Book".join(n+1), "w") as f2:
n += 1
f2.write(calc_time)
if order == 'file':
news_file(name, path=paths)
elif order == 'dir':
news_dir(name, path=paths)
elif order == 'pb':
news_python_book(name)
报错内容:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
news(("hello"), paths="d:")
File "C:\Users\WL\OneDrive\桌面\new.py", line 38, in news
news_file(name, path=paths)
File "C:\Users\WL\OneDrive\桌面\new.py", line 21, in news_file
with open("w", str(path.join(str(each)))) as f:
ValueError: invalid mode: '(d:'d:hd:ed:ld:ld:od:'d:,d:)'
问题出在代码的open函数调用上。open函数的第一个参数应该是文件路径,第二个参数应该是文件打开模式。在代码中,open函数的第一个参数是字符串"w",这是一个无效的模式。正确的写法是将"w"作为字符串的一部分,与文件路径拼接起来。另外,代码中的calc_time函数和clac_time函数应该是同一个函数,这里拼写错误。下面是修正后的代码:
import time
import os
def news(*name, paths="books//Python_book", order='file'):
def calc_time():
f_time = ""
t = time.localtime()
dw = ["年", "月", "日", "时", "分", "秒"]
i = 0
for index in t:
f_time += str(index) + dw[ i]
i += 1
return f_time
def news_file(*name, path):
for each in name:
if os.path.isfile(os.path.join(str(path), str(each))):
print(str(each) + "已存在!")
else:
with open(os.path.join(str(path), str(each)), "w") as f:
f.write(calc_time())
def news_dir(*name, path):
for each in name:
if os.path.isdir(os.path.join(str(path), str(each))):
print(str(each) + "已存在!")
else:
os.mkdir(os.path.join(str(path), str(each)))
with open(os.path.join(str(path), str(each), "创建日期"), "w") as f:
f.write(calc_time())
def news_python_book(number):
with open("books//number", "r+") as f1:
n = int(f1.read())
for index in range(number):
with open("books//Python_Book" + str(n+1), "w") as f2:
n += 1
f2.write(calc_time())
if order == 'file':
news_file(*name, path=paths)
elif order == 'dir':
news_dir(*name, path=paths)
elif order == 'pb':
news_python_book(*name)
修正后的代码中,open函数的参数使用了os.path.join函数来拼接文件路径,保证了路径的正确性。另外,calc_time函数的拼写错误已经修正。
|
|