使用 python 面向对象的编程脚本打开文件的基本问题

basic trouble opening a file with python object oriented programming script

我是 OOP 的新手,在编写和执行将打开和读取文件的基本脚本时遇到问题。

我 运行 时收到错误 IOError: [Errno 2] No such file or directory: '--profile-dir'。这有什么问题,我该如何解决?

class testing(object):

    def __init__(self, filename):
        self.filename = filename
        self.words = self.file_to_text()

    def file_to_text(self):
        with open(filename, "r") as file_opened:
            text = file_opened.read()
            words = text.split()
            return words

alice = testing("alice.txt").file_to_text()
print alice

此外,如果我希望能够从命令行生成此可执行文件,这些调整应该可以使它工作,对吗?

import sys
...
alice = testing(sys.argv[1]).file_to_text()
print alice

line to actually input in command line to run it-----> ./testing.py alice.txt

在此先感谢大家。

你在某处定义了 filename = '--profile-dir',它正在 with open(filename, "r") 中使用,使用 with open(self.filename, "r") 来使用你在 class 中定义的实际属性:

filename = "foob"
class testing(object):  
    def __init__(self, filename):
        self.filename = filename
        self.words = self.file_to_text()
    def file_to_text(self):
        print(filename)
        with open(filename, "r") as file_opened:
            text = file_opened.read()
            words = text.split()
            return words 

输出:

foob
IOError: [Errno 2] No such file or directory: 'foob'

您的代码将在您进行更改后使用 sys.argv 正常工作:

import sys

class testing(object):
    def __init__(self, filename):
        self.filename = filename
        self.words = self.file_to_text()
    def file_to_text(self):
        with open(self.filename, "r") as file_opened:
            text = file_opened.read()
            words = text.split()
            return words
alice = testing(sys.argv[1]).file_to_text()
print alice

:~$ python main.py input.txt
['testing']

如果你想使用 ./#!/usr/bin/env python 放在顶部并 chmod +x 使其可执行。

您也可以使用 itertools.chain:

避免调用读取和拆分
from itertools import chain
class testing(object):
    def __init__(self, filename):
        self.filename = filename
        self.words = self.file_to_text()
    def file_to_text(self):
        with open(self.filename, "r") as file_opened:
            return list(chain.from_iterable(line.split() for line in file_opened))
  1. 错误可能是因为传递给脚本的参数,在 运行 配置设置中搜索 --profile-dir 并将其删除。
  2. 要从命令行传递参数,请将以下代码附加到您的脚本中

    if __name__ == '__main__': if len(sys.argv) > 1: alice = testing(sys.argv[1]).file_to_text()

with open(filename, "r") as file_opened:

这从一个名为 filename 全局变量 中读取,而不是您在初始化程序中设置的变量。据推测,它的值为 '--profile-dir',因此它会尝试打开具有该名称的文件并在该文件不存在时抛出错误。您想要将 filename 替换为 self.filename 以获取 class 实例中的字段。

此代码使用 linecache 并读取您想要的任何行,而无需真正打开文件。速度很快!

import linecache

class Read_Line(object):
    def __init__(self, file_input, line):
        self.file_input = file_input
        self.line = line

    def Line_to_Text(self):
        Words = linecache.getline(self.file_input, self.line)
        Words = Words.split()
        return Words

Test = Read_Line("File.txt", 3)
print Test.Line_to_Text()