AttributeError: 'list' object has no attribute 'split' in Python - python

I am having problems with this bit of code
import csv
temp = open("townsfile.csv", "r")
towns = temp.read()
temp.close()
print(towns)
eachTown = towns.split("\n")
print (eachTown)
record = eachTown.split(",")
for line in eachTown:
record = eachItem.split(",")
print(record)
newlist=[]
newlist.append(record)
newlist=[]
for eachItem in eachTown:
record = eachItem.split(",")
newlist.append(record)
print(newlist)
It returns this error
Traceback (most recent call last):
File "N:/Python practice/towns.py", line 10, in <module>
record = eachTown.split(",")
AttributeError: 'list' object has no attribute 'split'
Can anyone help me with this

The csv module gives you this text parsing functionality, you do not need to do it yourself.
import csv
with open("townsfile.csv", "r") as f:
reader = csv.reader(f, delimiter=',')
towns = list(reader)
print(towns)
The problem you have is that list.split() does not exist, you are trying to use str.split() but you already split it into a list of strs. You would need to do it for every str in the list.

eachTown = towns.split("\n")
This code return list. List don't have attribute split. You should replace
record = eachTown.split(",")
like this
records = [rec.split(",") for rec in eachTown]
But better if you start using module csv for read this file.

Related

How can I remove unnecssary characters from a csv file

I want to remove all the special characters from the csv file. I tried in many ways but couldn't fix it
import re
data=("C:/Users/Niroshima/Desktop/Research/post.csv")
for i in data.values():
i = re.sub(r'[^\x00-\x7F]', '', i)
print(i)
And this error came up
AttributeError
Traceback (most recent call last)
<ipython-input-17-ee7352e82dd3> in <module>
----> 1 for i in data.values():
2 i=re.sub(r'[^\x00-\x7F]','',i)
3 print(i)
AttributeError: 'str' object has no attribute 'values'
data is just your file name, try opening the file and changing each line like so:
file_name = "C:/Users/Niroshima/Desktop/Research/post.csv"
with open(file_name) as f:
for line in f:
l = re.sub(r'[^\x00-\x7F]','', line)
print(l)
If you want this data in another file, then you have to write each l to a different file

How to apply regex sub to a csv file in python

I have a csv file I wish to apply a regex replacement to with python.
So far I have the following
reader = csv.reader(open('ffrk_inventory_relics.csv', 'r'))
writer = csv.writer(open('outfile.csv','w'))
for row in reader:
reader = re.sub(r'\+','z',reader)
Which is giving me the following error:
Script error: Traceback (most recent call last):
File "ffrk_inventory_tracker_v1.6.py", line 22, in response
getRelics(data['equipments'], 'ffrk_inventory_relics')
File "ffrk_inventory_tracker_v1.6.py", line 72, in getRelics
reader = re.sub(r'\+','z',reader)
File "c:\users\baconcatbug\appdata\local\programs\python\python36\lib\re.py",
line 191, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object
After googling to not much luck, I would like to ask the community here how to open the csv file correctly so I can use re.sub on it and then write out the altered csv file back to the same filename.
csv.reader(open('ffrk_inventory_relics.csv', 'r')) is creating a list of lists, and when you iterate over it and pass each value to re.sub, you are passing a list, not a string. Try this:
import re
import csv
final_data = [[re.sub('\+', 'z', b) for b in i] for i in csv.reader(open('ffrk_inventory_relics.csv', 'r'))]
write = csv.writer(open('ffrk_inventory_relics.csv'))
write.writerows(final_data)
If you don't need csv you can use replace with regular open:
with open('ffrk_inventory_relics.csv', 'r') as reader, open('outfile.csv','w') as writer:
for row in reader:
writer.write(row.replace('+','z'))

Getting AttributeError: 'file' object has no attribute 'rstrip'

I don't understand why I'm getting this message:
Traceback (most recent call last):
File "/Users/rrmenon/Desktop/untitled text 4.py", line 5, in
list=fh.rstrip().split()
AttributeError: 'file' object has no attribute 'rstrip'
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
list=fh.rstrip().split()
if word in lst: continue
lst.append(word)
lst.sort()
print lst
I'm trying to get all words in these strings (four or five sentences), copied in together in one list. What my Coe currently does (edited based on the suggestions below), is return each sentence as a separate list within a list. How Do I combine the words in the sentence?
The error is pretty clear: fh is a file object, which doesn't have a rstrip method.
Looks like you want line.rstrip() instead.
The message is very clear: you're trying to do fh.rstrip(), but rstrip works on strings, not files; what you probably wanted to do is:
list = line.rstrip().split()

Extracting value data from multiple JSON strings in a single file

I know I am missing the obvious here but I have the following PYTHON code in which I am trying to-
Take a specified JSON file containing multiple strings as an input.
Start at the line 1 and look for the key value of "content_text"
Add the key value to a new dictionary and write said dictionary to a new file
Repeat 1-3 on additional JSON files
import json
def OpenJsonFileAndPullData (JsonFileName, JsonOutputFileName):
output_file=open(JsonOutputFileName, 'w')
result = []
with open(JsonFileName, 'r') as InputFile:
for line in InputFile:
Item=json.loads(line)
my_dict={}
print item
my_dict['Post Content']=item.get('content_text')
my_dict['Type of Post']=item.get('content_type')
print my_dict
result.append(my_dict)
json.dumps(result, output_file)
OpenJsonFileAndPullData ('MyInput.json', 'MyOutput.txt')
However, when run I receive this error:
AttributeError: 'str' object has no attribute 'get'
Python is case-sensitive.
Item = json.loads(line) # variable "Item"
my_dict['Post Content'] = item.get('content_text') # another variable "item"
By the way, why don't you load whole file as json at once?

python 3 csv file - attribute error

I am trying to read in the following csv file:
https://github.com/eljefe6a/nfldata/blob/master/stadiums.csv
I copied and pasted the contents it into excel and save it as a csv file because it is in a unix format.
and I get the following attribute error message
Any help appreciated. Thank you.
import sys
import csv
with open('stadium.csv', newline='') as csvfile:
readCSV = csv.reader(csvfile,delimiter=',')
for line in readCSV:
line = line.strip()
unpacked = line.split(",")
stadium, capacity, expanded, location, surface, turf, team, opened, weather, roof, elevation = line.split(",")
results = [turf, "1"]
print("\t".join(results))
Error:
Traceback (most recent call last):
File "C:/Python34/mapper.py", line 31, in <module>
line = line.strip()
AttributeError: 'list' object has no attribute 'strip'
When you call .strip() on line it doesn't work because line is a list type object. Strip is method that only applies to strings. If I'm correct about what you're trying to do the correct way to unpack the variables would be:
stadium, capacity, expanded, location, surface, turf, team, opened, weather, roof, elevation = line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7], line[8], line[9], line[10]
The above works because you put the location of the value in the list (line) within the brackets and unpack the values into their respective variables.
Then call you can do:
stadium.split()
for example.
When you are using csv module, with delimiter as ',' and when you do -
for line in readCSV:
line is actually each row in the csv, and the row would be a list of all elements in that row, delimited by ',' . You actually do not need to strip or split them again.
You can try -
import sys
import csv
with open('stadium.csv', newline='') as csvfile:
readCSV = csv.reader(csvfile,delimiter=',')
for line in readCSV:
stadium, capacity, expanded, location, surface, turf, team,opened, weather, roof, elevation = line
results = [turf, "1"]
print("\t".join(results))
Please do make sure that the elements you do unpacking are there in the csv.
The CSV reader already separates all the fields for you. That is, your line variable is already a list, not a string, so there's nothing to strip and nothing to split. Use line the way you intended to use unpacked.
That's why you're using the csv package in the first place, remember.

Categories