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.
Related
import pickle
usernames_passwords = open("username_password.pck", "wb")
customer_login = []
pickle.dump(customer_login, usernames_passwords, "wb")
usernames_passwords.close()
I'm trying to dump a list of usernames and passwords into a pickle file, and I keep getting a type error. Can anyone explain what I'm doing wrong?
Traceback (most recent call last):
File "/Users/andy/PycharmProjects/python/venv/scratch.py", line 4, in <module>
pickle.dump(customer_login, usernames_passwords, "wb")
TypeError: an integer is required (got type str)
Process finished with exit code 1
From the pickle docs:
The optional protocol argument, an integer, tells the pickler to use the given protocol; supported protocols are 0 to HIGHEST_PROTOCOL. If not specified, the default is DEFAULT_PROTOCOL. If a negative number is specified, HIGHEST_PROTOCOL is selected.
So, your third argument is using the format you'd use to open a file, but pickle works differently and expects an int. See the docs here.
I am new to Python and am wondering how to address the following attribute error. I believe I need to define/declare the file variable? Thanks for any suggestions, here is my script:
AttributeError Traceback (most recent call last)
in
51
52 # Write methods to print to Financial_Analysis_Summary
---> 53 file.write("Financial Analysis")
54 file.write("\n")
55 file.write("----------------------------")
AttributeError: 'str' object has no attribute 'write'
From your code and error, I think You've defined the variable 'file' as a string. Aslo there is no attribute write() in the class str. Hence, the reason for this error. For more information, include the whole script i.e., mainly the use of variable 'file'. I think you can use print() to print the above mentioned details or create a new class with a method inside to print your desired things
It looks like you've somehow defined file as a string rather than a file. What you should to is define it thus:
summary_file=open("C:/someFolder/someOtherFolder/Financial_Analysis_Summary.txt",
mode='r+', encoding='utf8')
and then write to it.
The first argument to the open function is the file path. The mode is how you want to access the file: 'r' lets you read the file and nothing else (and throws a FileNotFoundError if the file doesn't yet exist; the others just create it), 'r+' lets you write to the file while leaving its preexisting text in place (although if you write to the middle of the file you'll still overwrite whatever was there), 'w' deletes what was in the file and lets you write to it, 'a' lets you write text only to the end of the file, 'w+' and 'a+' are the same as w and a except they let you read from the file; you can add b to the end of any of these to interact with the file in the form of bytes rather than strings. The encoding should only matter if you plan to use Unicode characters, in which case set it to the same encoding you'll use to view the file (usually 'utf8') to avoid garbling non-ASCII characters.
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])
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.
How do I skip a line of records in a CSV when using a DictReader?
Code:
import csv
reader = csv.DictReader(open('test2.csv'))
# Skip first line
reader.next()
for row in reader:
print(row)
Error:
Traceback (most recent call last):
File "learn.py", line 3, in <module>
reader.next()
AttributeError: 'DictReader' object has no attribute 'next'
You use next(reader) instead.
Source: csv.DictReader documentation
Since Python 2.6 you should use next(foo) instead of foo.next().
It was considered a mistake in python2 to have the method called next() instead of __next__()
next(obj) now calls obj.__next__() just like str, len etc. as it should.
You usually wouldn't call obj.__next__() directly just as you wouldn't call obj.__str__() directly if you wanted the string representation of an object.
Handy to know if you find yourself writing unusual iterators