如何用python创建文件_如何使用Python创建新的文本文件
我正在python中練習.txt文件的管理.我一直在閱讀它,發現如果我嘗試打開一個不存在的文件,它將在程序執行的同一目錄上創建它.問題是,當我嘗試打開它時,我收到此錯誤:
IOError: [Errno 2] No such file or directory:
‘C:\Users\myusername\PycharmProjects\Tests\copy.txt’.
我甚至嘗試在錯誤中看到指定路徑.
import os
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
my_file = os.path.join(THIS_FOLDER, 'copy.txt')
解決方法:
看起來你在調用open時忘記了mode參數,試試w:
file = open("copy.txt", "w")
file.write("Your text goes here")
file.close()
默認值為r,如果文件不存在則將失敗
'r' open for reading (default)
'w' open for writing, truncating the file first
其他有趣的選擇是
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
– 編輯 –
正如chepner在下面的評論中所述,更好的做法是使用withstatement(它保證文件將被關閉)
with open("copy.txt", "w") as file:
file.write("Your text goes here")
標簽:python,python-2-7
來源: https://codeday.me/bug/20191007/1868977.html
總結
以上是生活随笔為你收集整理的如何用python创建文件_如何使用Python创建新的文本文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java new对象 =null_在Ja
- 下一篇: opengl实现三维动画简单代码_使用P