Python 写入文件时出现问题,导致错误22

Python 写入文件时出现问题,导致错误22,python,Python,我正在学习python和编程,在学习教程的同时,我遇到了一个导致错误22的问题。谢谢大家! OSError: [Errno 22] Invalid argument: 'logs/2021-05-14 13:56:36.txt' 代码如下: def Write_to_file(Date,net_worth,filename='{}.txt'.format(datetime.now().strftime("%Y- %m-%d %H:%M:%S"))):

我正在学习python和编程,在学习教程的同时,我遇到了一个导致错误22的问题。谢谢大家!

OSError: [Errno 22] Invalid argument: 'logs/2021-05-14 13:56:36.txt'
代码如下:

    def Write_to_file(Date,net_worth,filename='{}.txt'.format(datetime.now().strftime("%Y- 
    %m-%d %H:%M:%S"))): 
    for i in net_worth: 
    Date += " {}".format(i)
    #print(Date)
    if not os.path.exists('logs'):
    os.makedirs('logs')
    file = open("logs/"+filename, 'a+')
    file.write(Date+"\n")
    file.close()
这是错误和回溯

Traceback (most recent call last):
File "C:\Users\Conor\Documents\GitHub\RL-Bitcoin-trading-bot\RL-Bitcoin-trading-bot_2\RL- 
Bitcoin-trading-bot_2.py", line 176, in <module>
Random_games(test_env, visualize=True, train_episodes = 1, training_batch_size=300)
File "C:\Users\Conor\Documents\GitHub\RL-Bitcoin-trading-bot\RL-Bitcoin-trading-bot_2\RL- 
Bitcoin-trading-bot_2.py", line 156, in Random_games
state, reward, done = env.step(action)
File "C:\Users\Conor\Documents\GitHub\RL-Bitcoin-trading-bot\RL-Bitcoin-trading-bot_2\RL- 
Bitcoin-trading-bot_2.py", line 118, in step
Write_to_file(Date, self.orders_history[-1])
File "C:\Users\Conor\Documents\GitHub\RL-Bitcoin-trading-bot\RL-Bitcoin-trading- 
bot_2\utils.py", line 27, in Write_to_file
file = open("logs/"+filename, 'a+')
OSError: [Errno 22] Invalid argument: 'logs/2021-05-14 13:56:36.txt'
[Finished in 2.9s with exit code 1]
[shell_cmd: python -u "C:\Users\Conor\Documents\GitHub\RL-Bitcoin-trading-bot\RL-Bitcoin- 
trading-bot_2\RL-Bitcoin-trading-bot_2.py"]
[dir: C:\Users\Conor\Documents\GitHub\RL-Bitcoin-trading-bot\RL-Bitcoin-trading-bot_2]
回溯(最近一次呼叫最后一次):
文件“C:\Users\Conor\Documents\GitHub\RL比特币交易机器人\RL-Bitcoin-trading-bot\u 2\RL-
Bitcoin-trading-bot_2.py“,第176行,in
随机游戏(测试环境,可视化=True,训练集=1,训练批量=300)
文件“C:\Users\Conor\Documents\GitHub\RL比特币交易机器人\RL-Bitcoin-trading-bot\u 2\RL-
比特币交易机器人2.py“,第156行,随机游戏
状态、奖励、完成=环境步骤(操作)
文件“C:\Users\Conor\Documents\GitHub\RL比特币交易机器人\RL-Bitcoin-trading-bot\u 2\RL-
Bitcoin-trading-bot_2.py”,第118行,步骤
将\写入\文件(日期,self.orders\历史记录[-1])
文件“C:\Users\Conor\Documents\GitHub\RL比特币交易机器人\RL比特币交易-
bot_2\utils.py”,第27行,在Write_to_文件中
文件=打开(“日志/”+文件名,“a+”)
OSError:[Errno 22]无效参数:“logs/2021-05-14 13:56:36.txt”
[在2.9秒内完成,退出代码为1]
[shell\u cmd:python-u”C:\Users\Conor\Documents\GitHub\RL比特币交易机器人\RL比特币-
trading-bot_2\RL-Bitcoin-trading-bot_2.py“]
[dir:C:\Users\Conor\Documents\GitHub\RL比特币交易机器人\RL-Bitcoin-trading-bot2]
[路径:C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\system32\Wbem;C:\WINDOWS\system32\WindowsPower Shell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files\Intel\WiFi\bin;C:\Program 文件\通用文件\英特尔\WirelessCommon;C:\Program Files (x86)\QuickTime\QTSystem;C:\Program 文件(x86)\PuTTY;C:\Program Files\MATLAB\R2020b\bin;C:\Program Files(x86)\NVIDIA 公司\PhysX\Common;C:\Program Files\NVIDIA公司\NVIDIA NvDLISR;C:\Users\Conor\AppData\Local\Programs\Python\Launcher;C:\Users\Conor\AppData\Local\Pr grams\Python\Python38-32\Scripts;C:\Users\Conor\AppData\Local\Programs\Python\Python38- 32;C:\Users\Conor\AppData\Local\Microsoft\WindowsApps;C:\Users\Conor\AppData\Local\GitHubDesk
top\bin]

Windows下的文件名中不允许使用冒号

使用另一个字符分隔这些时间分量

另外,您的
filename=…
并没有达到预期效果,因为在导入模块时,参数默认值只计算一次

你可能在找

def Write_to_file(Date, net_worth, filename=None):
    if not filename:
        filename = "{}.txt".format(datetime.now().strftime("%Y-%m-%d %H-%M-%S"))
    Date += " ".join(str(i) for i in net_worth)
    os.makedirs("logs", exist_ok=True)
    with open("logs/" + filename, "a+") as file:
        print(Date, file=file)

非常感谢,这很有效!再次感谢,问题肯定出在冒号上,现在正在写入文件。唯一的问题是,它现在将每个日志条目拆分为不同的文件,而不是创建一个文件。您可能希望将文件名更改为不包含秒数,那么…为什么要使用
print()
而不是
file.write()
?@amc它自己处理新行。这是否回答了您的问题?