pycharm如何設定python環境
pycharm配置python環境的方法:首先指定可寫入的模式,程式碼為【f1.write('hello boy!')】;然後關閉相關文件即可將快取中的資料寫入到文件中,代碼為【[root@node1 ~]# hello boy!】。
本教學操作環境:windows7系統、python3.9版,DELL G3電腦。
pycharm配置python環境的方法:
直接的寫入資料是不行的,因為預設開啟的是'r' 只讀模式
>>> f.write('hello boy') Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: File not open for writing >>> f <open file '/tmp/test.txt', mode 'r' at 0x7fe550a49d20>
應該先指定可寫入的模式
>>> f1 = open('/tmp/test.txt','w') >>> f1.write('hello boy!')
但此時資料只寫到了快取中,並未儲存到文件,而且從下面的輸出可以看到,原先裡面的配置被清空了
[root@node1 ~]# cat /tmp/test.txt [root@node1 ~]#
關閉這個檔案即可將快取中的資料寫入到檔案中
>>> f1.close() [root@node1 ~]# cat /tmp/test.txt [root@node1 ~]# hello boy!
注意:這一步需要相當慎重,因為如果編輯的檔案存在的話,這一步操作會先清空這個文件再重新寫入。那如果不要清空檔案再寫入該如何做呢?
使用r 模式不會先清空,但是會替換掉原先的文件,如下面的例子:hello boy! 被替換成hello aay!
>>> f2 = open('/tmp/test.txt','r+') >>> f2.write('\nhello aa!') >>> f2.close() [root@node1 python]# cat /tmp/test.txt hello aay!
如何實現不替換?
>>> f2 = open('/tmp/test.txt','r+') >>> f2.read() 'hello girl!' >>> f2.write('\nhello boy!') >>> f2.close() [root@node1 python]# cat /tmp/test.txt hello girl! hello boy!
可以看到,如果在寫之前先讀取一下文件,再進行寫入,則寫入的資料會添加到文件末尾而不會替換掉原先的文件。這是因為指標引起的,r 模式的指標預設是在文件的開頭,如果直接寫入,則會覆蓋來源文件,透過read() 讀取文件後,指標會移到文件的末尾,再寫入數據就不會有問題了。這裡也可以使用a 模式
>>> f = open('/tmp/test.txt','a') >>> f.write('\nhello man!') >>> f.close() >>> [root@node1 python]# cat /tmp/test.txt hello girl! hello boy! hello man!
關於其他模式的介紹,請見下表:
相關免費學習推薦:python影片教學
以上是pycharm如何設定python環境的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)