[英]I can't read in a file and write out to a file in Python
import sys
def main():
tclust_blue = open("ef_blue.xpk")
tclust_original = open("tclust.txt","a")
for line in tclust_blue.readlines():
if "{}" in line:
tclust_original.write(line)
我在讀取文件“ ef_blue.xpk”時遇到麻煩,該文件與我的Python腳本位於同一目錄,與tclust.txt
文件位於同一目錄。 錯誤提示:
IO錯誤:[ErrNo 2]沒有這樣的文件或目錄:'ef_blue.xpk'
另外我也不知道我的代碼是否正確。 我有一個名為tclust.txt的文本文件,並且在名為ef_blue.xpk的文件中有行,我想從ef_blue.xpk中獲取值(而不是行)並將其放入tclust.txt中。
我執行文件的方式是通過使用命令nfxsl readin.py
通過終端執行。
您的腳本使用相對路徑,並且相對路徑不會根據“腳本所在的位置”進行解析,而是針對執行代碼時當前工作目錄所處的位置進行解析。 如果您不想依賴當前的工作目錄(很顯然您不依賴),則需要使用絕對路徑。
在這里,您有兩個選擇:將文件(或目錄...)路徑作為命令行參數傳遞,或使用sys.path
模塊的功能和魔術變量__file__
來構建絕對路徑:
whereami.py:
import os
import sys
print("cwd : {}".format(os.getcwd()))
print("__file__ : {}".format(__file__))
print("abs file : {}".format(os.path.abspath(__file__)))
here = os.path.dirname(os.path.abspath(__file__))
print("parent directory: {}".format(here))
sibling = os.path.join(here, "somefile.ext")
print("sibling with absolute path: {}".format(sibling))
輸出示例:
bruno@bigb:~/Work$ python playground/whereami.py
cwd : /home/bruno/Work
__file__ : playground/whereami.py
abs file : /home/bruno/Work/playground/whereami.py
parent directory: /home/bruno/Work/playground
sibling with absolute path: /home/bruno/Work/playground/somefile.ext
附帶說明:
首先,請始終關閉文件-確定,當前的CPython實現會在程序退出時將其關閉,但這只是實現細節,而不是規范的一部分。 確保文件關閉的最簡單方法是with
語句:
with open("somefile.ext") as input, open("otherfile.ext", "w") as output:
# do something with output and input here
# ...
#此時(在with
塊之外),#兩個文件都將關閉。
第二點, file.readlines()
將讀取內存中的整個文件。 如果只想遍歷文件中的每一行,而只遍歷文件本身,則可以避免占用內存:
with open("somefile.ext") as f:
for line in f:
print f
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.