繁体   English   中英

我无法在Python中读入文件并写出到文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM