Python Counter throwing cannot concatenate 'str' and 'list' objects - python

So I have some python code that is supposed to confirm how many lines (\n) I have in a file before processing. I have this code:
doc_contents = context.getFileService().readFile(filePath)
context.logDebug("doc_contents is of type:"+str(type(doc_contents)))
context.logDebug("CSV file read:"+doc_contents)
if Counter(doc_contents)['\n'] < 2 or (Counter(doc_contents)['\n'] == 1 and !doc_contents.endswith('\n')):
The doc_contents are read fine. The type is "unicode" and the CSV file is printed to the logs just fine. I can even see the ^m in vi so I know there are the correct new line characters. But this line keeps throwing cannot concatenate 'str' and 'list' objects message. I am very new to python but I don't see where I am trying to use a list
Any Ideas?

Related

TypeError: object of type 'IndirectObject' has no len()

I'm trying to get contents in pdf file using the python PyPDF2 package. But getting this error.
TypeError: object of type 'IndirectObject' has no len()
This is happening to a particular file. It's working fine with the remaining files. Is there any reasonable logic behind it?
attached more details of the error

Python 'int' object is not subscriptable - casting doesnt work as expected

I'd like to read the last line of a file and then get a substring of it for printing it out.
I've made different approaches but none of them worked.
file_temp = os.system('cat "/myfile.csv"|tail -1')
# line looks like that ['08/19/2020 22:30:14', '26.1', '53.2', '82']
test = str(file_temp[25:-16])
print (test)
#same for
print (file_temp[2])
this results in the following error:
temp_test = str(file_temp[25:-16])
TypeError: 'int' object is not subscriptable
With or without casting, it doesn't seem to work.
If you want to read the last line of a file, this is the wrong command. You have to open the file, read it, and get the line you wanted:
file_temp = open("/myfile.csv","r")
lines = file_temp.readlines()
file_temp.close()
print(lines[-1])

Python fwrite function error: a bytes like object is required, not str

There is several errors "a bytes-like object is required, not 'str'. But none of them is related to mine. I open the file using open(filename, "w"), not "wb". The code is like 150 lines long. The beginning of the code is to assign the input of command line into parser args.
The args.result is an empty txt file which I want to write my result onto.
I open it using open.
I think the following code should be enough to illustrate my question. Before the line 65, the code is writing two functions to be used in calculation but I think it should be irrelevant to the bug.
In the code, I manually create the file 'save/results/result.txt' in the command terminal. Then I open the file in the line 132.
The remaining code is
A interesting bug happens that the line 158 runs OK. "begin training\n" can be written into file. Then for the line 165, during the first time of loop, it is OK and "aa\n" can be written into file. But during the second loop, the program end with an error "a bytes-like" object is required, not 'str'. The error message is as following.
Anyone could provide a help of that?
Quite thanks.
I've never had trouble with similar code, but if you want a quick fix, I'd bet making a string named f_text and adding to it within the for loop, then writing all of it to the file after the last iteration of the for loop would be a simple way to circumvent the problem.
IE:
f_text = ""
for epoch in range(your_range):
# Do calculations
print(the_stuff_you_wanted_to)
f_text += the_stuff_you_wanted_to + "\n"
f.write(f_text)
I'm mostly posting this to act as a quick fix though. I feel that there's probably a better solution and could help more if you show more of your code, like where you actually initialize f.

Trying to open a text file and create a list of lines separating the between sentences.

Using Python 3.6 and Spyder. This one is driving me crazy and should be easy, but I am stumped. I am trying to open a text file and create a list of the lines. I am trying to separate the lines based on periods. I want to be able to do something like list_of_lines[25]. I keep getting the following error AttributeError: '_io.TextIOWrapper' object has no attribute 'decode'. I tried to open the file normally and then use .split(), but kept getting ascii errors.
Any suggestions or pointing me in the right direction would be great.
with open("SORROWS_OF_YOUNG_WERTHER.txt") as book:
text_file = book.decode('ascii')
list_of_lines = [word.split('.') for word in text_file.readlines()]
print(list_of_lines)
Unless you are opening with the binary flag 'b'. The file is already text, so there is no need to decode.
This should work fine:
with open("SORROWS_OF_YOUNG_WERTHER.txt") as book:
list_of_lines = [line.decode('utf-8').split('.') for line in book.readlines()]
print(list_of_lines)
Be aware that the output is however going to split each line at each period.

'_csv.writer' object has no attribute 'write'

I am not sure what the problem is here. I have a csv file I want to filter. I want to remove all lines starting with '#' and all lines where the third column is the string 'chrM'. Im basically setting my code up to be like the answer here:
TypeError: expected a character buffer object
But Im getting an error.
import re
import csv
inputSamFile = 'excerpt'
outSamFile = 'filternoM'
with open(inputSamFile) as inputSam, open(outSamFile, 'wt') as outSam:
inputSamCont = csv.reader(inputSam, delimiter = '\t')
outSamCont = csv.writer(outSam, delimiter = '\t')
for line in inputSamCont:
if line[0].startswith('#'):
continue
elif line[2] == 'chrM':
continue
else:
outSamCont.write(line)
Traceback (most recent call last):
File "filterMito.py", line 19, in
outSamCont.write(ProcessLine(line))
AttributeError: '_csv.writer' object has no attribute 'write'
What am I doing wrong
You may be looking for .writerow().
I also ran into this problem, as the documentation I was following used .write(), but csv.writer objects use .writerow().
The error tells you everything you need to know.
AttributeError: '_csv.writer' object has no attribute 'write'
In your code, you create the object:
outSamCont = csv.writer(outSam, delimiter = '\t')
then try to call the .write() method:
outSamCont.write(line)
(or, as it is in the traceback
outSamCont.write(ProcessLine(line))
I'm not sure why you have posted different code to what you're running).
However, that object, a csv.writer, does not have the method write, hence the error message. See the documentation for csv.writer objects for the list of methods they do have, and choose the appropriate one.

Categories