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

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])

Related

AttributeError: 'NoneType' object has no attribute 'strip'..while editing CSV

Consider the following code:
import xlwings as xw
directory("C:\\Users\Ritesh\PycharmProjects\BS\Test1.csv")
wb = xw.Book(directory)
sht = wb.sheets['Test1']
count = 1
for row in range(2, 200):
A = 'A%s' % row
B = 'B%s' % row
C = 'C%s' % row
D = 'D%s' % row
rays = sht.range(A).value
line = rays.strip().strip(" ")
code = line.split(" ")[0]
sht.range('D1').value = 'Code'
sht.range(D).value = code
Please help me to solve this, as it is showing an error like:
"AttributeError: 'NoneType' object has no attribute 'strip'"
First, this line here
directory("C:\\Users\Ritesh\PycharmProjects\BS\Test1.csv")
perhaps looks like a valid Python syntax, but it shouldn't be valid because that is a function call directory(x) with x as a parameter. It wasn't valid in Python2 & it's not valid in Python3 because there's no function directory declared before that line. So by that logic your error would not have been AttributeError since the error occured before the line wb = xw.Book(directory) is reached. Please edit and include the complete exception error.
Second, I just did a quick search in xlwings documentation and I couldn't find any function directory in it. Was directory some function you didn't include in code you posted here? Please double check if it's a cut+paste problem of accidentally left out or explain how you got that directory function.
ps: your path looks wrong too, iirc in windows the path would be C:\ with a single backslash instead of double, but that might still works, my recollection of windows is quite fuzzy.

os.ftruncate() is showing some error while execution error like TypeError: a bytes-like object is required

import os,sys
sr=os.open("sri.txt",os.O_RDWR|os.O_CREAT)
os.write(sr,"This is the test-This is test")
os.ftruncate(sr,10)
os.lseek(sr,0,0)
str=os.read(sr,100)
print("Read string is:",str)
os.close(sr)
print("closed the file successfully!!")
In python3 all strings are automatically Unicode.
So I can see two ways to fix it.
one is append "b" before writing the string as shown below.
os.write(sr,b"This is the test-This is test")
Or
Another is call encode() as shown below.
str = "This is the test-This is test"
ret = os.write(sr,str.encode())
For better understanding of strings behavior in python3 look into below tutorial
http://pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/

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

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?

Issues with saving json in Python: TypeError: 'int' object is not subscriptable

I am currently having issues trying to save to a .json file and reload it later. The program seems to save somewhat properly, but I get an error when attempting to reload it later on. I am unsure of what I am doing wrong and have attempted to fix it for roughly 30 minutes now. Please note that I am a novice to Python and would appreciate simplified responses.
This is the json file (which will never be the same).
{"stat.playOneMinute":44,"stat.leaveGame":1,"stat.timeSinceDeath":44,"achievement.exploreAllBiomes":{"value":0,"progress":["ForestHills"]}}
This is the error I get when attempting to reload the json file later:
Traceback (most recent call last):
File "C:\Users\oiest\Desktop\Code\Minecraft Editor\v1.0.0\MCEditor.py", line 91, in <module>
MainMenu()
File "C:\Users\oiest\Desktop\Code\Minecraft Editor\v1.0.0\MCEditor.py", line 26, in MainMenu
EditWorld()
File "C:\Users\oiest\Desktop\Code\Minecraft Editor\v1.0.0\MCEditor.py", line 51, in EditWorld
EditProcess()
File "C:\Users\oiest\Desktop\Code\Minecraft Editor\v1.0.0\MCEditor.py", line 69, in EditProcess
print('stat.timeSinceDeath is currently ' + str(data['stat.timeSinceDeath']))
TypeError: 'int' object is not subscriptable
This is the code that causes the error:
with open(stats_path + json_file, "r+") as jsonFile:
data = json.load(jsonFile)
print(data)
print('')
print('What do you wish to edit?')
print('stat.timeSinceDeath')
user_input = input('Edit Stat: ')
if user_input == 'stat.timeSinceDeath':
print('stat.timeSinceDeath is currently ' + str(data['stat.timeSinceDeath']))
print('')
user_input = int(input('New Stat: '))
data['stat.timeSinceDeath'] = user_input
jsonFile.write(json.dumps(data))
jsonFile.seek(0) # rewind
jsonFile.write(json.dumps(data['stat.timeSinceDeath']))
jsonFile.truncate()
print(data['stat.timeSinceDeath'])
The error means that what's in your data file is just an integer. How did it get that way? Well, the problem is here:
jsonFile.write(json.dumps(data))
jsonFile.seek(0) # rewind
jsonFile.write(json.dumps(data['stat.timeSinceDeath']))
jsonFile.truncate()
You write out the new file, then rewind and write out just the timeSinceDeath over top of it. Which is an integer. So the next time you run the script, the JSON data is just the integer and so you get the error about subscripting an integer.
You can even see this very clearly from your print(data) call. (Good idea, adding a print to help debug. But it's even better to actually pay attention to it!)
To avoid this, don't overwrite your data file with just an integer. Take those two middle lines out. And put the original JSON back in the file.

'_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