How to Print this statment in to a txt file - python

I am trying to write a txt file but I am getting a TypeError.
How do I go about this? Here is my code below:
yesterdays_added = f1_set - f2_set
yesterdays_removed = f2_set -f1_set
with open('me{}{}{}.txt'.format(dt.year, '%02d' % dt.month, '%02d' % dt.day), 'w') as out:
for line in todays:
if line in yesterdays_added:
out.write( 'Removed', line.strip())
elif line in yesterdays_removed:
out.write ('Added', line.strip())
for line in yesterdays:
if line in yesterdays_added:
out.write ('Removed', line.strip())
elif line in yesterdays_removed:
out.write ('Added', line.strip())
This is the error I am getting:
out.write ('Added', line.strip())
TypeError: function takes exactly 1 argument (2 given)

You need to concatenate those together.
out.write("Added "+line.strip()) # Or out.write("Added {}".format(line.strip()))
For example,
>>> "Added "+"abc\n".strip()
'Added abc'
From The Python Docs
f.write(string) writes the contents of string to the file, returning
None.
Whenever in doubt, use help().
write(...)
write(str) -> None. Write string str to file.
This says that write() only takes in one argument. (Whereas you provide 2, hence the error)

As the error message suggests, write takes only one argument. If you want to write two things, make two calls to write, or concatenate them with +.

You received this error because the write method takes one argument of type string.
The writelines method, however, accepts one argument of type iterable.
The writelines method is the preferred method in this case, unless you would like to format the output string.
writelines example:
lines_to_write = ('Removed', line.strip(),)
open.writelines(lines_to_write)
write example:
line_to_write = '{0}...fancy formatting...{1}'.format('Removed', line.strip(),)
open.write(line_to_write)
Documentation:
http://docs.python.org/2/library/stdtypes.html#file.write
http://docs.python.org/2/library/stdtypes.html#file.writelines

Related

Error in JSON file reading : write() argument must be str, not generator

I'm reading content from a JSON file and appending it to a text file . I'm getting the following error :
' write() argument must be str, not generator ' when I run this code and I'm not able to correct it .
with open('stackExchangeAPI.json','r') as json_file:
tags_list = []
data = json.load(json_file)
for i in range(0,99):
for j in range(0,99):
tags = data[i]["items"][j]["tags"]
with open('tags.txt','a+') as tags_file:
tags_file.seek(0)
d = tags_file.read(100)
if len(d) > 0 :
tags_file.write("\n")
tags_file.write(f'{tags[i]}' for i in range(0,(len(tags)-1)))
The error is from the last line ' tags_file.write(f'......) '
Can someone please help me rectify this ?
You're trying to write the for loop to the file. Try changing the last line to:
[tags_file.write(f'{tags[i]}') for i in range(0,(len(tags)-1))]
As it says, you are trying to write a generator, you must first convert it to a string, probably by using join:
out = ''.join(f'{tags[i]}' for i in range(0,(len(tags)-1)))
tags_file.write(out)

'/' understood as a float?

I am looping through a pandas dataframe and trying to append the result on a conditional statement. However, my code seems to be posing a problem stopping me from append what I want although it prints fine but displays the error in the end. here is my code below:
counta=[]
for line in ipcm_perf['Alarms']:
if '/' in line:
print (line)
the error I get is the following :
2 for line in ipcm_perf['Alarms']:
----> 3 if ('/') in line:
4 print (line)
5
TypeError: argument of type 'float' is not iterable
I really do not know why Python is flagging that line. where's the float? Everything is being printed but with error at the bottom. It is stopping from appending.
your problem is that you are trying to check if there is a string (/) in a floating number (line), and Python does not like that.
That's because when you write "/" in some_string Python iterates through each char of some_string, but he can iterate through a floating number.
you can double check this by simply running:
if '/' in 3.14:
print("something")
output:
TypeError: argument of type 'float' is not iterable
I suppose that you're searching for a / because you've seen that somewhere in the column. If that's the case, it probably is in a string, and if that's the case, a quick&dirty way to clean your data can be:
if type(line) == str:
if "/" in line:
print(line)
else:
print("I am not a string")
and with line = 3.14, it returns:
I am not a string
and with line = "4/2", it returns:
I am a string

Python String Replace Error

I have a python script that keeps returning the following error:
TypeError: replace() takes at least 2 arguments (1 given)
I cannot for the life of me figure out what is causing this.
Here is part of my code:
inHandler = open(inFile2, 'r')
outHandler = open(outFile2, 'w')
for line in inHandler:
str = str.replace("set([u'", "")
str = str.replace("'", "")
str = str.replace("u'", "")
str = str.replace("'])", "")
outHandler.write(str)
inHandler.close()
outHandler.close()
Everything that is seen within double quotations needs to be replaced with nothing.
So set([u' should look like
This is what you want to do:
for line in inHandler:
line = line.replace("set([u'", "")
line = line.replace("'", "")
line = line.replace("u'", "")
line = line.replace("'])", "")
outHandler.write(line)
On the documentation, wherever it says something like str.replace(old,new[,count]) the str is an example variable. In fact, str is an inbuilt function, meaning you never want to change what it means by assigning it to anything.
line = line.replace("set([u'", "")
^This sets the string equal to the new, improved string.
line = line.replace("set([u'", "")
^ This is the string of what you want to change.
There are two ways to call replace.
Let us start by defining a string:
In [19]: s = "set([u'"
We can call the replace method of string s:
In [20]: s.replace("u'", "")
Out[20]: 'set(['
Or, we can call the replace of the class str:
In [21]: str.replace(s, "u'", "")
Out[21]: 'set(['
The latter way requires three arguments because str. That is why you received the error about missing arguments.
What went wrong
Consider the code:
for line in inHandler:
str = str.replace("set([u'", "")
str = str.replace("'", "")
str = str.replace("u'", "")
str = str.replace("'])", "")
First, note the goal is to replace text in line but nowhere in the calls to replace is the variable line used for anything.
The first call to replace generates the error:
>>> str.replace("set([u'", "")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: replace() takes at least 2 arguments (1 given)
Used in the above form, str.replace interprets its first argument as the string to replace. It is as if you wrote:
"set([u'".replace("")
In other words, it thinks that set([u' is the string to operate on and the replace function was given just one argument: the empty string. That it why the message is replace() takes at least 2 arguments (1 given).
What you need is to operate on the variable line:
line = line.replace("set([u'", "")
And so on for the remaining lines in the loop.
Conclusion: you have two issue:
error: wrong syntax for str.replace
abuse: the Python reserved key str
error: wrong syntax for str.replace
for error TypeError: replace() takes at least 2 arguments (1 given)
the root cause is:
your code
str = str.replace("set([u'", "")
intension is to use str.replace do replace work
the correct (one) syntax is:
newStr = oldStr.replace(fromStr, toStr[, replaceCount])
corresponding to your code, could be:
replacedLine = line.replace("set([u'", "")
Note: another syntax is:
newStr = str.replace(oldStr, fromStr, toStr[, replaceCount])
for full details please refer another post's answer
abuse: the Python reserved key str
background knowledge
str is Python reserved key word
means: the name of String class in Python 3
str has many builtin functions
such as: str.replace(), str.lower()
also means: you should NOT use str as normal variable/function name
so your code:
for line in inHandler:
str = str.replace("set([u'", "")
should change to (something like this):
for line in inHandler:
newLine = line.replace("set([u'", "")
or
for line in inHandler:
newLine = str.replace(line, "set([u'", "")
I think this should work.
for s in inHandler:
s = s.replace("set([u'", " ") ## notice the space between the quotes
s = s.replace("'", " ")
s = s.replace("u'", " ")
s = s.replace("'])", " ")
Please refrain from using built-in data types as variables (like you have used str).
You could compress the four lines of replace code
str = str.replace("set([u'", "")
str = str.replace("'", "")
str = str.replace("u'", "")
str = str.replace("'])", "")
as,
str = re.sub(r"set\(\[u'|u'|'\]\)|'", r"", str)
Example:
>>> import re
>>> string = "foo set([u'bar'foobaru''])"
>>> string = re.sub(r"set\(\[u'|u'|'\]\)|'", r"", string)
>>> string
'foo barfoobar'
I modified your code as below:
inHandler = open('test.txt', 'r')
outHandler = open('test1.txt', 'w')
data = ''
for line in inHandler.readlines():
print 'src:' + line
line = line.replace("set([u'", "")
line = line.replace("u'", "")
line = line.replace("'])", "")
line = line.replace("'", "")
data += line
print 'replace:' + line
outHandler.write(data)
inHandler.close()
outHandler.close()
And I tested it. Result:
src:set([u'adg',u'dafasdf'])
replace:adg,dafasdf
src:set([u'adg',u'dafasdf'])
replace:adg,dafasdf
src:set([u'adg',u'dafasdf'])
replace:adg,dafasdf
if you are referring to str.replace (string) inbuild function in python then
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new.
If the optional argument count is given, only the first count occurrences are replaced.
Means you need to give 2 values.
And you are using line as variable so you can try.
local_string = ''
for line in inHandler:
local_string = line
local_string = local_string.replace("set([u'", "")
local_string = local_string.replace("'", "")
local_string = local_string.replace("u'", "")
local_string = local_string.replace("'])", "")

how can I make a file created in a function readable by other functions?

I need the contents of a file made by some function be able to be read by other functions. The closest I've come is to import a function within another function. The following code is what is what I'm using. According to the tutorials I've read python will either open a file if it exists or create one if not.What's happening is in "def space" the file "loader.py" is duplicated with no content.
def load(): # all this is input with a couple of filters
first = input("1st lot#: ") #
last = input("last lot#: ") #
for a in range(first,last+1): #
x = raw_input("?:")
while x==(""):
print " Error",
x=raw_input("?")
while int(x)> 35:
print"Error",
x=raw_input("?")
num= x #python thinks this is a tuple
num= str(num)
f=open("loader.py","a") #this is the file I want to share
f.write(num)
f.close()
f=open("loader.py","r") #just shows that the file is being
print f.read() #appened
f.close()
print "Finished loading"
def spacer():
count=0
f=open("loader.py","r") #this is what I thought would open the
#file but just opens a new 1 with the
#same name
length=len(f.read())
print type(f.read(count))
print f.read(count)
print f.read(count+1)
for a in range(1,length+1):
print f.read(count)
vector1= int(f.read(count))
vector2 = int(f.read(count+1))
if vector1==vector2:
space= 0
if vector1< vector2:
space= vector2-vector1
else:
space= (35-vector1)+vector2
count=+1
b= open ("store_space.py","w")
b.write(space)
b.close()
load()
spacer()
this what I get
1st lot#: 1
last lot#: 1
?:2
25342423555619333523452624356232184517181933235991010111348287989469658293435253195472514148238543246547722232633834632
Finished loading # This is the end of "def load" it shows the file is being appended
<type 'str'> # this is from "def spacer" I realized python was creating another
# file named "loader.py with nothing in it. You can see this in the
#error msgs below
Traceback (most recent call last):
File "C:/Python27/ex1", line 56, in <module>
spacer()
File "C:/Python27/ex1", line 41, in spacer
vector1= int(f.read(count))
ValueError: invalid literal for int() with base 10: ''tion within another function but this only causes the imported function to run.
The file probably has content, but you're not reading it properly. You have:
count=0
#...
vector1= int(f.read(count))
You told Python to read 0 bytes, so it returns an empty string. Then it tries to convert the empty string to an int, and this fails as the error says, because an empty string is not a valid representation of an integer value.

Trouble concatenating two strings

I am having trouble concatenating two strings. This is my code:
info = infl.readline()
while True:
line = infl.readline()
outfl.write(info + line)
print info + line
The trouble is that the output appears on two different lines. For example, output text looks like this:
490250633800 802788.0 953598.2
802781.968872 953674.839355 193.811523 1 0.126805 -999.000000 -999.000000 -999.000000
I want both strings on the same line.
There must be a '\n' character at the end of info. You can remove it with:
info = infl.readline().rstrip()
You should remove line breaks in the line and info variables like this :
line=line.replace("\n","")
readline will return a "\n" at the end of the string 99.99% of the time. You can get around this by calling rstrip on the result.
info = infl.readline().rstip()
while True:
#put it both places!
line = infl.readline().rstip()
outfl.write(info + line)
print info + line
readline's docs:
Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line)...

Categories

Resources