str object has no attribute append [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
import nltk
file = open('SMSm.txt', 'r')
file2 = open('SMSw.txt', 'w')
for line in file.readlines():
if 'Rs' in line:
line.append(file2)
I am getting an attribute error in the last line of my code. I basically want all the lines with 'Rs' in it. Some of the lines have Rs5000 and some have format as Rs 5000. I want both the line to be appended in the new file. Any help would be appreciated.

You have your understanding about methods all mixed up.
If you want to write to a file object, then you must use the file.write() method; it is a member of the file object. Strings know nothing about files and don't care about files, so strings do not have any methods to do with files.
To add your selected lines to file2 then, you need to call file2.write(line):
for line in file.readlines():
if 'Rs' in line:
file2.write(line)
You may have gotten confused with lists; list objects do have a list.append() method.

Strings have no append() method, to concatenate strings use the + operator
"string" + "string"

Related

Python nested list from file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Let's say I have the following .txt file:
"StringA1","StringA2","StringA3"
"StringB1","StringB2","StringB3"
"StringC1","StringC2","StringC3"
And I want a nested list in the format:
nestedList = [["StringA1","StringA2","StringA3"],["StringB1","StringB2","StringB2"],["StringC1","StringC2","StringC3"]]
so I can access StringB2 for example like this:
nestedList[1][1]
What would be the best approach? I do not have a tremendous amount of data, maybe 100 lines at max, so I don't need a database or something
You can this sample code:
with open('file.txt') as f:
nestedList = [line.split(',') for line in f.readlines()]
print(nestedList[1][1])
file = open('a.txt').read()
file
l=[]
res = file.split('\n')
for i in range(len(res)):
l.append(res[i].split(','))
print(l[1][1])
Assuming your file name as a.txt is having data in same format as you specified in question, i.e newline seperated so that we can add nested list, and data inside is ,(comma) seperated. Above code will give you the right output.

Why is reading from a file not working after using a function? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
My code is supposed to find the occurrence of words in a text. For some reason, after using this function, the reading method from this specific textwon't work(empty lists for .readlines() method and nothing for .read()). The code is:
def counter(new):
words = dict()
lines=new.readlines()
for line in lines:
text=line.split()
for word in text:
if word not in words:
words[word]=1
else: words[word]+=1
return [tuple(x) for x in words.items()]
I haven't found any mistake that can cause this.
I am assuming new is the result of calling open(..), which should be a file handle that you are passing into the function. Calling readlines() is exhausting it, so trying to read from the file using the same handle won't work. Either open a new handle, or you can call new.seek(0) (better option than opening a completely new handle - although there are some cases where the same handle will be returned again, but lets not dive too deep into that here) to move the index to the beginning of the file.

Count characters in each line of a file? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Any tips on how to count the amount of characters in each line of a text file, to then compare them using python?
It would be helpful to have an idea of what the end goal of your code is. What information do you want to gain from comparing the number of characters on a line? I would have written this as a comment, but it's not yet an option for me since I just joined.
If you're completely lost and don't know where to begin, here are some general bits of code to get you started (this is using Python 3.x):
file = open("YourFileName.txt", "r")
stringList = file.readlines()
The first line will open (read, hence the "r") the file in question. The second line of code goes through each line in the file and assigns them to a variable I called stringList. stringList is now a list, in which each element is a string corresponding to one line of your text file.
So,
print(stringList)
should return
['line0', 'line1', 'line2', 'line3', etc...]
It's possible that stringList could look like
['line0\n', 'line1\n', 'line2\n', 'line3\n', etc...]
depending on how your file is formatted. In case you didn't know, the '\n' is a newline character, equivalent to hitting enter on the keyboard.
From there you can create another list to hold the length of each line, and then loop through each element of stringList to store the lengths.
lengthList = []
for line in stringList:
lengthList.append(len(line))
len(line) takes the number of characters in a string and converts it to the equivalent integer value. Your lengthList will then contain how many characters are on each line, stored as ints. If there are '\n's, you may want to use len(line) - 1, depending on what you want to do with the lengths.
I hope this is helpful; I can't help with the comparisons until you provide some code and explain more specifically what you want to accomplish.

How to make my python script accepts multiple positional arguments? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Suppose that I would like my python program to accept 2 positional arguments:
1. The path to an input file
2.The path to a word dictionary, which is also a txt file.
Can anyone teach me how to go about doing that?
import sys
print('Name of the script: {0}'.format(sys.argv[0]))
if len(sys.argv) == 3:
inputfile_path = sys.argv[1]
dictionary_path = sys.argv[2]
print('First parameter: {0}'.format(inputfile_path))
print('Second parameter: {0}'.format(dictionary_path))
https://docs.python.org/2/library/sys.html
Your question is a bit vague so I'm just going to answer what I think you meant.
I'll assume that you have a function as such:
def function(string1, string2):
''' string 1 and string2 are paths to an input file and a dictionary respectively'''
Now in general to read a file you use:
file1 = open(string1,'r')
# After opening the file you loop over lines to do what you need to.
for line in file:
# Do what you need to
I'm not sure what you want to do with the input file so I'm going to leave it at that.
To load a dictionary from a string we use the eval() function. It actually runs a string. Now each line in the dictionary stored as a text file is a string so all you have to do is loop through the entire file (using the for line in file method from before) and run eval to get back a dictionary.
For example try this simple code:
#assume string2 is what you get back from the looping
string2 = str({'jack': 4098, 'sape': 4139})
dic = eval(string2)
print dic
Hopefully I've pointed you in the right direction. Since I'm not sure what exactly you need to do, I can't really help you more.

Python function,issue with input file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have function written by a colleague working in same field. So I know I should write script to execute python code,but issue of how the format of the input bbfile looks like bothers me.As I see fidlines read all the content,correct?My may concern is bbfile(tab delimited in my case),should it have three columns one for freq,other for breal and third for bimag?
def bbcalfunc(bbfile,nfreqlst):
fid=file(bbfile,'r')
fidlines=fid.readlines()
#define the delimiter
if bbfile.find('.txt')>=0:
delimiter='\t'
elif bbfile.find('.csv')>=0:
delimiter=','
freq=[]
breal=[]
bimag=[]
for ii in range(1,len(fidlines)):
linestr=fidlines[ii]
linestr=linestr.rstrip()
linelst=linestr.split(delimiter)
if len(linelst)>2:
freq.append(float(linelst[0]))
breal.append(float(linelst[1]))
bimag.append(float(linelst[2]))
else:
pass
freq=np.array(freq)
breal=np.array(breal)
bimag=np.array(bimag)
nfreq=np.log10(np.array(nfreqlst))
brinterp=interpolate.splrep(freq,breal)
brep=1E3*interpolate.splev(nfreq, brinterp)
biinterp=interpolate.splrep(freq,bimag)
bip=1E3*interpolate.splev(nfreq, biinterp)
return brep,bip
The format of the input file depends on the extension that you use, a .txt file will be a Tab Separated Values (tsv) file while a .csv file will be a Comma Separated Values (csv) file (please note that this is not a general convention, it is something that was decided by that colleague of yours that wrote the function, or maybe it's a local convention).
Each line of the file is usually composed by three {tab,comma} separated values, i.e., frequency, real part and imaginary part of a complex value.
I said usually composed because the code silently discards all the
lines for which the element count is less than three.
There is something here and there that can be streamlined in the code,
but it's inessential.
Rather, to answer your question re closing the file, change the first part
of the function to
def bbcalfunc(bbfile,nfreqlst):
#define the delimiter
if bbfile.find('.txt')>=0:
delimiter='\t'
elif bbfile.find('.csv')>=0:
delimiter=','
# slurp the file
with file(bbfile,'r') as fid:
fidlines=fid.readlines()
...

Categories