在Python中写入文件时发生IOError [英] IOError when writing to file in Python

查看:125
本文介绍了在Python中写入文件时发生IOError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 <$ 

当我尝试执行下面的写入文件时,出现如下所示的错误...我在做什么错误? c $ c>#创建一个写入文件的方法。

f = open(C:\ Users \QamarAli\Documents\afaq's stuff\myFile.txt,r +)
f.write('0123456789abcdef')

这是错误:

<$ p $ (< code> Traceback(最近一次调用的最后一个):
< module>中的第1行文件< interactive input>
IOError:[Errno 22] invalid mode('r +')or filename:C:\\Users\\QamarAli\\Documents\x07faq's stuff\\myFile.txt
>>>


解决方案

尝试使用 os。路径 os.sep 来构建windows上的文件路径:

  import os 

file_path = os.path.join(C:+ os.sep,Users,QamarAli,Documents,afaq's stuff, myFile.txt)
print file_path
print os.path.exists(file_path)


When I try to execute below for writing to file, I get an error as shown below... What am I doing wrong?

# create a method that writes to a file.

f = open("C:\Users\QamarAli\Documents\afaq's stuff\myFile.txt", "r+")
f.write('0123456789abcdef')

Here is the error:

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
IOError: [Errno 22] invalid mode ('r+') or filename: "C:\\Users\\QamarAli\\Documents\x07faq's stuff\\myFile.txt"
>>> 

解决方案

Try to use os.path and os.sep to constructs file paths on windows:

import os

file_path = os.path.join("C:" + os.sep, "Users", "QamarAli", "Documents", "afaq's stuff", "myFile.txt")
print file_path
print os.path.exists(file_path)

这篇关于在Python中写入文件时发生IOError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆