TypeError: cannot concatenate 'str' and 'int' objects f.write python - python-2.7

I want to make the script save the result to the save.txt file
I am running with python2.7 and they are writing an error
Traceback (most recent call last): File "point9.py", line 7, in <module> f.write("" + data + "" + "\n") TypeError: cannot concatenate 'str' and 'int' objects
Code:
data = 3673256654
print(data)
f = open("save.txt", 'a')
f.write("" + data + "" + "\n")
f.close()

This expression doesn't do what you want:
"" + data + "" + "\n"
Prefer
f"{data}\n"
Some years ago they
sunsetted
the interpreter you're using.
I don't know offhand if f-strings
were ever back ported to python2.
You could use str(data) + "\n" for same effect.
Or any of the several .format() variants.
(Not sure why you appended empty string a couple
of times, as that does literally nothing.)

Related

Getting TypeError trying to open() a file in write mode with Python

I have a Python script that in my mind should:
Open a file
Save its content in a variable
For each line in the variable:
Edit it with a regular expression
Append it to another variable
Write the second variable to the original file
Here is a MWE version of the script:
# [omitting some setup]
with open(setFile, 'r') as setFile:
olddata = setFile.readlines()
newdata = ''
for line in olddata:
newdata += re.sub(regex, newset, line)
with open(setFile, 'w') as setFile:
setFile.write(newdata)
When I run the script I get the following error:
Traceback (most recent call last):
File C:\myFolder\myScript.py, line 11, in <module>
with open(setFile, 'w') as setFile:
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
As far as I can understand, Python is complaining about receiving the setFile variable as an argument of open() because it isn't of the expected type, but then why did it accept it before (when I only read the file)?
I suppose that my mistake is quite evident but, as I am a neophyte in Python, I can't find out where it is. Could anyone give me a help?
just curious why you are using the same variable name for your file and then as your filehandler and then again in your next with function.
_io.TextIOWrapper is the object from your previous open, which has been asssigned to the setFile variable.
try:
with open(setFile, 'r') as readFile:
olddata = readFile.readlines()
newdata = ''
for line in olddata:
newdata += re.sub(regex, newset, line)
with open(setFile, 'w') as writeFile:
writeFile.write(newdata)

how to solve python issue with NoneType

When the following code runs, its getting type error as follows:
Traceback (most recent call last):
File "Example.py", line 174, in <module>
for i,sentence in enumerate(clusters[cluster]):
TypeError: 'NoneType' object has no attribute '__getitem__'
How to solve this issue?
if __name__ == "__main__":
sent=open('/Desktop/word2vec_original/input.txt', 'r').read()
sentences=sent_tokenize(sent)
print
nclusters= 3
clusters = cluster_sentences(sentences, nclusters)
for cluster in range(nclusters):
clusterSentence = []
for i,sentence in enumerate(clusters[cluster]):
posTaggedSentence = pos_tag(word_tokenize(sentences[sentence]))
posTaggedSentenceStr = (' '.join(word + '/' + pos for word, pos in posTaggedSentence))
posTaggedSentence.append(posTaggedSentenceStr.strip())
clusterSentence.append(posTaggedSentenceStr)
The problem is that clusters value is None. You have to first verify if it is not None:
for cluster in range(nclusters):
clusterSentence = []
if clusters:
for i,sentence in enumerate(clusters[cluster]):

Python Regex Issue Involving "TypeError: expected string or bytes-like object" [duplicate]

This question already has answers here:
TypeError: expected string or buffer
(5 answers)
Closed 3 years ago.
I've been trying to parse a text file and manipulate it with regular expressions.
This is my script:
import re
original_file = open('jokes.txt', 'r+')
original_file.read()
original_file = re.sub("\d+\. ", "", original_file)
How to fix the following error:
Traceback (most recent call last):
File "filedisplay.py", line 4, in <module>
original_file = re.sub("\d+\. ", "", original_file)
File "C:\Python32\lib\re.py", line 167, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
And why am I getting this error?
original_file is a file object, you need to read it to get its contents, or the buffer that the regex requires.
Usually, it's also good that you use with (just so you don't have to remember closing the file), so you might end up with something like this:
import re
with open('jokes.txt', 'r+') as original_file:
contents = original_file.read()
new_contents = re.sub(r"\d+\. ", "", contents)
You will see I rawed the regex string up there in the code (I used an r before the regex string). That's also a good practice, because sometimes you will have to double escape some characters for them to behave properly as you expect them.
You call original_file.read(), but you don't assign that value to anything.
>>> original_file = open('test.txt', 'r+')
>>> original_file.read()
'Hello StackOverflow,\n\nThis is a test!\n\nRegards,\naj8uppal\n'
>>> print original_file
<open file 'test.txt', mode 'r+' at 0x1004bd250>
>>>
Therefore, you need to assign original_file = original_file.read():
import re
original_file = open('jokes.txt', 'r+')
original_file = original_file.read()
original_file = re.sub("\d+\. ", "", original_file)
I would also suggest using with like #Jerry, so that you don't have to close the file to save the writing.

How to include [] in python regex code?

I am using python 2.7.8 to write a small python code that reads a rule in a form A ==> B by using regex and return it in a form of 'A, B'.
This is my code:
import re
def fixp1(s):
pattern = re.compile("(?P<g1>([A-Z0-9a-z]|\?)*):(?P<g2>([A-Z0-9a-z]|\?)*)")
return eval(pattern.sub("('\g<g1>', '\g<g2>')", s))
x = "[ABCD:NP, [PQR:?TAG1]] ==> [XXX:?P]"
def readrule(r):
r.split("==>")
return [fixp1(r[0].strip()), fixp1(r[1].strip())]
When I test this code:
>>> readrule(x)
I got the following error message:
readrule(y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../patterns.py", line 12, in readrule
return [fixp1(r[0].strip()), fixp1(r[1].strip())]
File ".../patterns.py", line 5, in fixp1
return eval(pattern.sub("('\g<g1>', '\g<g2>')", s))
File "<string>", line 1
[
^
SyntaxError: unexpected EOF while parsing
>>>
I think this problem happened because I couldn't add '[' and ']' in here
([A-Z0-9a-z]|\?)
If that's right, how to do it? if not; where is my mistake?
Remove the eval command, the RegEx.sub returns a string which is your match with the replacements applied, you cannot evaluate the string. This yields the SyntaxError you are seeing.
If you want to include [] in your patterns, you need to escape them with \:
pattern = re.compile(r'[\[\]0-9]+')
would match strings like '[1234]'.

Is it possible to use output from raw_input() as a new file name?

I'm wondering if it's possible to use the return from raw_input()to create a file name?
What I have so far:
import os
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw()
ttnum=str(raw_input('Please enter ticket number: '))
ttnum
filename=askopenfilename()
abspath = os.path.abspath(filename)
dname = os.path.dirname(abspath)
os.chdir(dname)
f=open(filename)
contents=f.read()
file_len(filename)
file_scan(filename)
Portion of code that calls ttnum:
def file_len(filename):
#Count the number of line in the Text File
f1 = open(("WiFi Logs report for tt " + ttnum,'w'))
with open(filename) as f:
for i, l in enumerate(f):
pass
f1.write('Total number of lines in file: ' + str(i+1) + '\n' + '\n')
f1.close()
def file_scan(filename):
#List of issues to Scan For
f1 = open(("WiFi Logs report for tt " + ttnum,'a'))
I can enter input no problem (in this case 12345), but once it hits the code, I get the following:
Traceback (most recent call last):
File "M:\WiFi Log Scanner\WiFi_Log_Scanner.py", line 153, in <module>
file_len(filename)
File "M:\WiFi Log Scanner\WiFi_Log_Scanner.py", line 4, in file_len
f1 = open(("WiFi Logs report for tt " + ttnum,'w'))
TypeError: coercing to Unicode: need string or buffer, tuple found
I thought that the str() at the start would ensure that it is, well, a string and not a tuple?
Any insight would be appreciated.
Thanks,
Joe
Remove a layer of parentheses from open(("WiFi Logs report for tt " + ttnum,'a')):
open("WiFi Logs report for tt " + ttnum,'a')
With extra parentheses, you pass one argument to open, and this argument is a tuple: a pair of values, which is not what open expects for its first argument.
A side note (unrelated to your error): you don't have to chdir before you read a file (and your actual code only works when filename is already absolute, which the result of tk_getOpenFile is. chdir doesn't help anything here). And when chdir is necessary, it's error-prone (it introduces hidden state) and thread-unsafe.