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

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

Related

When isn't a list a list?

The following code returns a list, e.g. <class 'list'> in python. Everything I do to access that list fails
indexing list fails,
enumerating list fails
example if I just print(s)
['0.5211', '3.1324']
but if I access the indices
Traceback (most recent call last):
File "parse-epoch.py", line 11, in <module>
print("losses.add({}, {})".format(s[0], s[1]))
IndexError: list index out of range
Why can't I access the elements of the list?
import re
with open('epoch.txt', 'r') as f:
content = f.readlines()
content = [x.strip() for x in content]
for line in content:
s = re.findall("\d+\.\d+", line)
#print(s)
print("losses.add({}, {})".format(s[0], s[1]))
You should check what print(s) outputs again. Your issue is likely with a line where s does not contain a list with 2 values. If those values do not exist, then you cannot use them.

how to fix append() error after passing a list

I am trying to append the list to itself but it says "takes exactly one argument"
I have tried using other variables to store the splited line.
testfile = open(r'''C:\Users\shawa\Desktop\sampleg102.txt''' ,'r')
print(testfile)
word=list
for line in testfile:
line = line.lstrip()
word = word.append([1])
print(word)
and the error is
E:\vscode.source> python -u "e:\vscode.source\python\countingWords.py"
<_io.TextIOWrapper name='C:\\Users\\shawa\\Desktop\\sampleg102.txt'
mode='r' encoding='cp1252'>
Traceback (most recent call last):
File "e:\vscode.source\python\countingWords.py", line 7, in <module>
word = word.append([1])
TypeError: append() takes exactly one argument (0 given)
To explain the first mistake, take a look at this:
>>> list
<class 'list'>
>>> word = list
>>> word
<class 'list'>
>>> word = list()
>>> word
<list object at 0x...>
At the moment, you have only assigned the name list to the name word. You need to call the list constructor to actually create the list. Now, the method list.append() modifies the list in-place. It returns None and you don’t need to re-assign it.
word = list()
# word = '' works too
for line in testfile:
line = line.lstrip()
word.append([1])
print(word)
Your code will print a list of lists of 1s at the moment. If you meant to append the lines of the file, use
word.append(line)
Note that it’s preferable to use the literal [] empty list syntax rather than calling list() as it makes it very clear what is being created.
You are looking for word=list() not word=list. list is just a keyword, list() instantiates
You need to do this if you are trying to append line to list. In your code you are appending only [1] to the list word.
testfile = open(r'''C:\Users\shawa\Desktop\sampleg102.txt''' ,'r')
print(testfile)
word=list()
for line in testfile:
line = line.lstrip()
word.append(1) #or word.append(line[1]) according to use case
print(word)

Splitting and adding words from a file into a list, 'str' object cannot be interpreted as an integer error

I am not aware of the cause of this error, but I am trying to take the words within a file, read the lines, split them, and then add those words into a list and sort them. It is simple enough but I seem to be getting an error which states ''str' object cannot be interpreted as an integer' I am not aware of the cause for this error and would appreciate some assistance.
I haven't tried a lot of methods as I was sure this one would work and I don't have a good idea of how to go around it. The file I'm using contains this:
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
here is the code that I am using...
#userin = input("Enter file name: ")
try:
l = [] # empty list
relettter = open('romeo.txt', 'r')
rd = relettter.readlines()
# loops through each line and reads file
for line in rd:
#add line to list
f = line.split(' ', '/n')
l.append(f)
k = set(l.sort())
print(k)
except Exception as e:
print(e)
the results should print a sorted list of the words present in the poem.
Your giant try/except block prevents you from seeing the source of the error. Removing that:
› python romeo.py
Traceback (most recent call last):
File "romeo.py", line 9, in <module>
f = line.split(' ', '/n')
TypeError: 'str' object cannot be interpreted as an integer
You are passing '/n' as the second argument to the split() method, which is an integer maxsplit. Your line
f = line.split(' ', '/n')
does not work because only one string can be used for the split method, e.g.:
f = line.split(' ')
Note also that '\n' is a newline, not '/n'.
The error is caused when you split f = line.split(' ', '/n') instead do this f = line.split('\n')[0].split(' '). Also on the next statement I think you'lled want to extend not append
try:
l = [] # empty list
relettter = open('romeo.txt', 'r')
rd = relettter.readlines()
# loops through each line and reads file
for line in rd:
#add line to list
f = line.split('\n')[0].split(' ') ##<-first error
l.extend(f) ##<- next problem
k = set(sorted(l))
print(k)
except Exception as e:
print(e)
Though, a much better implementation:
l = [] # empty list
with open('romeo.txt') as file:
for line in file:
f = line[:-1].split(' ')
l.extend(f)
k = set(sorted(l))
print(k)
You should probably be using with in this case. It esentially manages your otherwise unmanaged resource. Here is a great explanation on it: What is the python keyword "with" used for?.
As for your problem:
with open(fname, "r") as f:
words = []
for line in f:
line = line.replace('\n', ' ')
for word in line.split(' '):
words.append(word)
This will read the text line by line and splits each line into words. The words are then added into the list.
If you're looking for a shorter version:
with open(fname, "r") as f:
words = [word for word in [line.replace('\n', '').split(' ') for line in f]]
This will give a list of words per sentence, but you can flatten and get all your words that way.

AttributeError: 'list' object has no attribute 'split' in 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.

Python - Error while trying to split line of text

I am having as issue while trying to split a line of text I get from .txt file. It is quite a big file, but I will paste only 2 lines, with original text
1307;Własność: udział 1/1<>GMINA TARNOWIEC<><> 211<>30-200 ZipCode;KS1J/00080000/2;861;Własność: udział 1/1<>GMINA TARNOWIEC<><> 211<>30-200 ZipCode;KS1J/00080990/2;
1306;Własność: udział 1/1<>Jan Nowak<>im. rodz.: Tomasz_ Maria<>Somewhere 2<>30-200 ZipCode;KW22222;861;Własność: udział 1/1<>GMINA TARNOWIEC<><>Tarnowiec 211<>30-200 ZipCode;KS1W/00080000/1;
Data I get from this file will be used to create reports, and _ and <> will be used for further formatting. I want to have the line split on ;
Problem is, I am getting error on 2 methods of splitting.
first, the basic .split(';')
dane = open('dane_protokoly.txt', 'r')
for line in dane:
a,b,c,d,e,f,g = line.split(';')
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)
I am getting an error after printing the first loop
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\Nowy folder\costam.py", line 36, in <module>
a,b,c,d,e,f,g = line.split(';')
ValueError: not enough values to unpack (expected 7, got 1)
Same with creating lists from this file (list looks like: ['1307', 'Własność: udział 1/1<>GMINA TARNOWIEC<><> 211<>30-200 ZipCode', 'KS1J/00080000/2', '861', 'Własność: udział 1/1<>GMINA TARNOWIEC<><> 211<>30-200 ZipCode', 'KS1J/00080990/2', '']
dane = plik('dane_protokoly.txt')
for line in dane:
a = line[0]
b = line[1]
c = line[2]
d = line[3]
e = line[4]
f = line[5]
g = line[6]
print(str(a))
print(str(b))
print(str(c))
print(str(d))
print(str(e))
print(str(f))
error I get also after properly printing the first line:
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\Nowy folder\costam.py", line 22, in <module>
b = line[1]
IndexError: list index out of range
Any idea why am I getting such errors?
Sometimes line.split(';') not giving 7 values to unpack for (a,b,c,...), So better to iterate like this ,
lst = line.split(';')
for item in lst:
print item
And there is a newline in between that's making the problems for you,
And the syntax that followed is a bad practice
You change your code like this,
for line in open("'dane_protokoly.txt'").read().split('\n'):
lst = line.split(';')
for item in lst:
print item
It's doesn't care about the newlines in between,
As Rahul K P mentioned, the problems are the "empty" lines in between your lines with the data. You should skip them when trying to split your data.
Maybe use this as a starting point:
with open(r"dane_protokoly.txt", "r") as data_file:
for line in data_file:
#skip rows which only contain a newline special char
if len(line)>1:
data_row=line.strip().split(";")
print(data_row)
Your second strategy didn't work because line[0] is essentially the whole line as it includes no spaces and the default is splitting at spaces.
Therefore there is no line[1] or line[2]... and therefore you get a list index out of range error.
I hope this helps. And I hope it solves your problem.

Categories