AttributeError: 'str' object has no attribute 'filename' in Python - python

I'm new to Python and currently learning, I had a task to do some reading and writing to files with a python script. The reading part of my script seems to work as expected however the write section is throwing an error. It's probably something trivial I have done but here is my code:
class LogMessage():
def __init__(self, filename):
self.filename = filename
def read(self):
inputFile = open(self.filename)
for line in inputFile:
print(line, end='')
def write(self):
outputFile = open(self.filename)
#writeInput = input('What data do you wish to write?:\n')
for line in writeInput:
print(line,file = outputFile, end='')
filename = LogMessage('new.txt')
filename.read()
writeInput = input('What data do you wish to write?:\n')
LogMessage.write(writeInput)
The read part works but taking user data and writing it to the file and gives this error:
Traceback (most recent call last):
File "/home/alex/workspace/Python/Learn Python/labEx9.py", line 22, in <module>
LogMessage.write(writeInput)
File "/home/alex/workspace/Python/Learn Python/labEx9.py", line 11, in write
outputFile = open(self.filename)
AttributeError: 'str' object has no attribute 'filename'
can anyone help me, thanks a lot.
Alex

You must call 'write' on 'filename', which is an instance of LogMessage, not on the LogMessage class.
Apart from this, there are other issues (e.g. 'writeInput' is not defined in method 'write')

If you get such errors while using flask check your html code( your_form.) and add this to your html :
<form method="POST" action="" enctype="multipart/form-data">
enctype="multipart/form-data" would help.

class LogMessage():
def __init__(self, filename):
self.filename = filename
def read(self):
inputFile = open(self.filename)
for line in inputFile:
print(line, end='')
def write(self):
writeInput = input('What data do you wish to write?:\n')
outputFile = open(self.filename, 'w')
for line in writeInput:
print(line, file = outputFile, end='')
filename = LogMessage('new.txt')
filename.write()
filename.read()

Related

TypeError while using ast

I am trying to read my dictionary(in my file) using ast
import ast
import os
class just_a_class():
def __init__(self, file,):
self.file = file()
self.read_file = open(self.file,'r+')
def read_file(self):
dict = ast.literal_eval(self.read_file.read())
return 'Input: \n\n {}'.format(dict)
the_class = just_a_class("dict.txt")
print(the_class.self.read_file())
Error:
Traceback (most recent call last):
File "c:/Users/Barış/Desktop/Onemli_Programlarim/Connection_PL/conn.py", line 13, in <module>
the_class = just_a_class("dict.txt")
File "c:/Users/Barış/Desktop/Onemli_Programlarim/Connection_PL/conn.py", line 6, in __init__
self.file = file()
TypeError: 'str' object is not callable
The code below is similar to what is used in the question. I've tried
to improve the readability by using common techniques and conventions,
such as using fname for the filename, instead of file, using a
context manager to open (and auto-close) the file, and capitalization
for class names. Also changed the flags to the open() call to be "r"
instead of "r+", as suggested by ShadowRanger.
import ast
class Just_a_class():
def __init__(self, fname):
self.fname = fname
def read_file(self):
with open(self.fname, 'r') as f:
dict = ast.literal_eval(f.read())
return 'Input: \n\n {}'.format(dict)
the_class = Just_a_class("dict.txt")
print(the_class.read_file())
# {'a': 5, 'b': 'hello'}

How to convert a normal function into a function inside a class?

I'm trying to organize my code I already have by implementing classes and execute methods on classes instantiations. I have put some hours into figuring out how to use classes, but still haven't figured it out. Could someone help me?
This is the original code:
def readSignalAcquisitionData(fileName):
f = open(fileName, 'r')
# dummy read
f.readline()
timeStamps = []
dataInput = []
for ln in f:
# parse info
timeStr, dataStr = ln.split(',')
timeStamps.append(float(timeStr))
dataInput.append(float(dataStr))
f.close()
return timeStamps, dataInput
And this is what I currently have:
class SignalDataIOUnit:
def __init__(self, fileName):
self.fileName = fileName
def readSignalAcquisitionData(self):
f = open(self.fileName, 'r')
self.timeStamps = []
self.dataInput = []
for ln in f:
# parse info
self.timeStr, self.dataStr = ln.split(',')
self.timeStamps.append(float(self.timeStr))
self.dataInput.append(float(self.dataStr))
f.close()
return self.timeStamps, self.dataInput
def writeFilteredData(self, fileName, timeStamps, dataOut):
pass
fileName="LabsWeek03_inputData.csv"
timeStamps, dataInput = SignalDataIOUnit.readSignalAcquisitionData(fileName)
print(timeStamps)
When I try running it through the terminal I get these error messages:
Traceback (most recent call last):
File "SignalDataEvaluationUnit_OOP.py", line 26, in <module>
timeStamps, dataInput = SignalDataIOUnit.readSignalAcquisitionData(fileName)
File "SignalDataEvaluationUnit_OOP.py", line 7, in readSignalAcquisitionData
f = open(self.fileName, 'r')
AttributeError: 'str' object has no attribute 'fileName'
As #deceze♦ says in comment, you haven't instantiated the class SignalDataIOUnit, that's why it doesn't work.
To make it work, you have 2 choices:
Instantiating SignalDataIOUnit object and call the method readSignalAcquisitionData:
timeStamps, dataInput = SignalDataIOUnit(fileName).readSignalAcquisitionData()
Use Python's #staticmethod decorator:
class SignalDataIOUnit:
def __init__(self, fileName):
self.fileName = fileName
#staticmethod
def readSignalAcquisitionData(fileName):
...
then just call it as usual
timeStamps, dataInput = SignalDataIOUnit.readSignalAcquisitionData(fileName)
yes, you should use like this
fileName="LabsWeek03_inputData.csv"
timeStamps, dataInput = SignalDataIOUnit(fileName).readSignalAcquisitionData()
print(timeStamps)

How to add custom information to json file with scrapy in python

I am exporting data from an item to a json file with srapy's jsonitemexporter. Now I would like to add some basic information about the data to the file, e.g. partner name or pagename.
Putting this code into
class BidPipeline(object):
file = None
def open_spider(self, spider):
self.file = open('data/'+ datetime.datetime.now().strftime ("%Y%m%d") + '_' + spider.name + '.json', 'wb')
self.exporter = JsonItemExporter(self.file)
# trying to add partner info
a = {'partner': 3}
line = json.dumps(a) + "\n"
self.file.write(line)
self.exporter.start_exporting()
Results in traceback:
yield self.engine.open_spider(self.spider, start_requests)
builtins.TypeError: a bytes-like object is required, not 'str'
My goal is to add some info to the json file before starting the export of the items, so later while processing the data one can determine e.g. the source.
What would be the best way to achieve this?
There error is pretty self explanatory here:
a bytes-like object is required, not 'str'
You open file to write bytes (wb) and you try to write string:
def open_spider(self, spider):
self.file = open(..., 'wb')
^^^^^
...
a = {'partner': 3}
line = json.dumps(a) + "\n"
^^^^
self.file.write(line)
To resolve this either open file as string file (just w instead of wb) or encode your line before writing it to file:
self.file.write(line.encode())
Preferably you should always use w when writing text and wb when writting bytes (e.g. image data)

How to avoid error using the chr function while decoding ASCII?

I've worked on a code to "encode" song lyrics pasted into a text file, using the ord function. This is the code below:
import os
filename = os.path.abspath("WeWillRockYou.txt")
out_file = open('WeWillRockYou2.txt', 'w')
readFile = open (filename, 'r')
for line in readFile:
for char in line:
if not char == "\n":
out_file.write(str(ord(char)))
else:
out_file.write(char)
out_file.close()
After, these song lyrics are put into a new text file, but as ASCII. Now I'm attemping to make a code which will "decode" the song lyrics and write them into a new text file as they were originally, however I get an error. The decode code in the one below:
import os
filename = os.path.abspath("WeWillRockYou2.txt")
out_file = open('WeWillRockYou3.txt', 'w')
readFile = open (filename, 'r')
for line in readFile:
for num in line:
if not num == "\n":
out_file.write(int(chr(num)))
else:
out_file.write(char)
out_file.close()
But I get the error:
Traceback (most recent call last):
line 16, in <module>
out_file.write(int(chr(num)))
TypeError: an integer is required
Any help on how to fix this would be greatly appreciated! Thankss!

Error while using '<file>.readlines()' function

The goal was to import the infile, read it, and print only two lines into the outfile.This is the code I had in IDLE:
def main():
infile = open('names.py', "r")
outfile = open('orgnames.py', "w")
for i in range (2):
line = ("names.py".readlines())
print (line[:-1], infile = outfile)
infile.close()
outfile.close()
main()
This is the error message I keep getting:
Traceback (most recent call last):
File "C:/Python33/studentnames6.py", line 11, in <module>
main()
File "C:/Python33/studentnames6.py", line 6, in main
line = ("names.py".readlines())
AttributeError: 'str' object has no attribute 'readlines'
I have used the function readlines in a similar situation before and it had worked fine. I don't understand why it's having an error now, or how to fix it.
The error is because names.py is a string, and not a file object. The following code should work for you:
def main():
infile = open('names.py', "r")
outfile = open('orgnames.py', "w")
# Prints the first two lines in outfile
for line in infile.readlines()[:2]:
outfile.write(line)
infile.close()
outfile.close()
main()

Categories