oop - basic trouble opening a file with python object oriented programming script -
i'm new oop , having trouble writing , executing basic script open , read file.
i'm getting error ioerror: [errno 2] no such file or directory: '--profile-dir'
when run this. what's wrong , how should fix it?
class testing(object): def __init__(self, filename): self.filename = filename self.words = self.file_to_text() def file_to_text(self): open(filename, "r") file_opened: text = file_opened.read() words = text.split() return words alice = testing("alice.txt").file_to_text() print alice
also, if i'd able make executable command line, these tweaks should make work, right?
import sys ... alice = testing(sys.argv[1]).file_to_text() print alice line input in command line run it-----> ./testing.py alice.txt
thanks in advance guys.
somewhere have filename = '--profile-dir'
defined, being used in with open(filename, "r")
, use with open(self.filename, "r")
use actual attribute have defined in 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) open(filename, "r") file_opened: text = file_opened.read() words = text.split() return words
output:
foob ioerror: [errno 2] no such file or directory: 'foob'
your code work fine using sys.argv once make change:
import sys class testing(object): def __init__(self, filename): self.filename = filename self.words = self.file_to_text() def file_to_text(self): open(self.filename, "r") 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']
if want use ./
put #!/usr/bin/env python
@ top , chmod +x
make executable.
you can avoid calling read , splitting using 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): open(self.filename, "r") file_opened: return list(chain.from_iterable(line.split() line in file_opened))
Comments
Post a Comment