I am trying to do something that should be very simple. I am a bit frustrated for why my code won't work, so any help is appreciated :).
My program reads in data, and then makes a dictionary that records the number of times a particular item occurs (I am using Twitter data and counting hashtag occurrences). I want to output the top tweets, and have found a nice easy way to do that using the following:
def main():
tweet_file = open(sys.argv[1])
tweet_dic = lines(tweet_file) #function that makes my dictionary
for i in range(0,10):
big_key = max(tweet_dic, key = lambda i: tweet_dic[i])
big_value = tweet_dic[big_key]
sys.stdout = big_key + " " + str(big_value)
del tweet_dic["big_key"]
tweet_file.close()
The error I get on using this is AttributeError: 'str' object has no attribute 'write'
Now I have outputted the two different values into terminal using print just fine, they can be put in two different print statements with no problems since I don't have to concatenate or anything. I have checked the two variables types, and as expected they are always str & int.
My understanding of the str(integer to convert) function is that you should be able to pass in an integer and get a string representation back! After it has been converted, I have been able to print out things like this in the past with no issues.
Things to consider that may be throwing it out - the big_key can sometimes be a string that was converted from Unicode by .encode('utf-8'). Otherwise the output from my file (printing on separate lines) looks like:
MTVHottest 60
KCAMexico 38
EXO 26
CD9 24
Unicode 19
Coders 18
AlonsoVillapandoTrendy 17
Unicode 14
Unicode 14
Any ideas? Thanks in advance!
The error you're getting is because of this: https://docs.python.org/2/library/sys.html#sys.stdout
stdout and stderr needn’t be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument.
stdout and stderr are the locations where the data is written, you aren't supposed to assign data itself to stdout, which is what it looks like you're doing.
As others have mentioned you would assign stdout to where you want and then use the print command to actually get the data to go there. But if all you're trying to do is print a line of text to a file then why not just open the file and write to it normally?
with open(tweet_file, 'w') as f:
f.write(big_key + " " + str(big_value))
The specific error you're getting is from the line:
sys.stdout = big_key + " " + str(big_value)
This is not how things are output to stdout.
Using a print would be the appropriate way to do that:
print(big_key + " " + str(big_value))
There are some other strange things in your code example, like for example using big_key and then "big_key" in quotes. So probably that's not the end of your bugs and errors.
Related
I have run into an issue where i can't format a string to be printed.
The function is suppossed to convert Binary into Text which is does brilliantly but the printed out result is formatted all the way the right and not the left.
I have tried resolving this by looking up how to format the string but im getting no luck. Im hoping someone can resolve this issue for me.
Heres the code:
elif Converter_Choice2 == str(3):
def Bin_to_Txt():
print("\nYour Message in Binary:")
bin_input = input("")
binary_int = int(bin_input, 2)
byte_number = binary_int.bit_length() + 7 // 8
binary_array = binary_int.to_bytes(byte_number, "big")
ascii_text = binary_array.decode()
clear()
print("\nYour Message in Text:")
print(ascii_text)
Bin_to_Txt()
I tried different ways to format it but im still new to Python 3. I tried putting "ascii_text" into another string to format it, so i could print that string but it didn't work.
ascii_text_formatted = ("{:<15}".format(ascii_text))
print(ascii_text_formatted)
Some advice for this would be great.
Heres a quick Binary code that can be used: 0100100001100101011011000110110001101111
The decoded version should say "Hello".
I managed to find the answer. If anyone else has this issue or something similar try this:
The issue was the variable "binary_array" was printing out invisible numbers before the printed answer in this case "Hello". Due to this it would print "Hello" all the way to the right as the invisible numbers where in front of it.
To fix this issue i added [34:] at the end of the "binary_array" string to remove those invisible numbers from the print. By adding [34:] it means the first 34 characters/numbers wont be printed even if they are invisible. So this can be any number that you need it to be. For example if i changed 34 to 35 it would remove the "H" from "Hello" and print "ello".
Heres some screenshots of the function block and printed responces from before and after adding [34:].
https://imgur.com/a/W25G1FZ
I am trying to read each line in proc.stdout.readline and send the lines over the network, for example:
data = b''
for line in iter(proc.stdout.readline, ''):
data += line
clientsocket.send(data)
When I run this code I seem to be stuck in a inifinite loop unable to escape to the line:
clientsocket.send(data)
Is there a more efficient way to read the data? I've tried also with a while loop and breaking 'if not line':
data = b''
while True:
line += proc.stdout.readline()
data += line
if not line:
break
clientsocket.send(data)
This seems to also produce the same results. Is there a more efficient way to read all of the data from proc.stdout.readline?
I've encountered the same very problem. The strange thing that in Python 2.7 it had no problem to converge and actually stop iterating.
During debug (in Python 3.5) I've noticed that all true lines returned with the '\n' character, whereas the line that wasn't suppose to arrive returned as an empty string, i.e. ''. So, I just added an if-clause checking against '' and breaking the loop if positive.
My final version looks as follows:
lines = []
for _line in iter(process.stdout.readline, b''):
if _line == '':
break
lines.append(_line)
One thing that might be worth to mention, is that I used universal_newlines=True argument upon subprocess.Popen(..) call.
The statement: iter(proc.stdout.readline, "") will do a blocking read until it recieves an EOF.
If you want to read all the lines, then you can just do:
data = b''
data = b"".join(proc.stdout.readlines())
There is no other solution than for the proc to produce lines faster.
If you want, you can read lines with timeout (i.e. you can wait to read a select number of characters, or timeout if that number of characters are not read).
Those answers can be found here:
https://stackoverflow.com/a/10759061/6400614 .
https://stackoverflow.com/a/5413588/6400614
I am a beginner in Python and was trying to make a small program to record changes in money. When I try and use information stored in the file 'amount.txt' an error occurs and states 'TypeError: must be str, not _io.TextIOWrapper' How can I fix this and still use the data from 'amount.txt'?
dollars = open("Amount.txt", "r")
print("Current Updated Total: ($" + dollars + ")")
^This is where the problem occurs
I expect the output to state 'Current Updated Total: ($100)'
The actual output however is 'TypeError: must be str, not _io.TextIOWrapper'
Close, you just need to read the contents of the file:
dollars = open("Amount.txt", "r").read()
The result of just open() is a file object, _io.TextIOWrapper; it services a container for doing different types of operations on the file in addition to reading its entire contents as you want to do in this case.
Also, in Python 3, "r" is the default mode, so you can just use:
dollars = open("Amount.txt").read()
I have a program that I created with two sections.
The first one copies a text file with an integer in the middle of the file name in this format.
file = "Filename" + "str(int)" + ".txt"
the user can create as many copies of the file that they would like.
The second part of the program is what I am having the problem with. There is an integer at the very bottom of the file that is to correspond with the integer in the file name. After the first part is done, I open each file one at a time in "r+" read/write format. So I can file.seek(1000) to about where the integer is in the file.
Now in my opinion the next part should be easy. I should just simply have to write str(int) into the file right here. But it wasn't that easy. It worked just fine doing it like that in Linux at home, but at work on Windows it proved difficult. What I ended up having to do after file.seek(1000) is write to the file using Unicode UTF-8. I accomplished this with this code snippet of the rest of the program. I will document it so that it is able to be understood what is going on. Instead of having to write this in Unicode, I would love to be able to write this in good old regular English ASCII characters. Eventually this program will be expanded to include a lot more data at the bottom of each file. Having to write the data in Unicode is going to make things extremely difficult. If I just write the data without turning it into Unicode this is the result. This string is supposed to say #2 =1534, instead it says #2 =ㄠ㌵433.
If someone can show me what I am doing wrong that would be great. I would love to just use something like file.write('1534') to write the data to the file instead of having to do it in Unicode UTF-8.
while a1 < d1 :
file = "file" + str(a1) + ".par"
f = open(file, "r+")
f.seek(1011)
data = f.read() #reads the data from that point in the file into a variable.
numList= list(str(a1)) # "a1" is the integer in the file name. I had to turn the integer into a list to accomplish the next task.
replaceData = '\x00' + numList[0] + '\x00' + numList[1] + '\x00' + numList[2] + '\x00' + numList[3] + '\x00' #This line turns the integer into Utf 8 Unicode. I am by no means a Unicode expert.
currentData = data #probably didn't need to be done now that I'm looking at this.
data = data.replace(currentData, replaceData) #replaces the Utf 8 string in the "data" variable with the new Utf 8 string in "replaceData."
f.seek(1011) # Return to where I need to be in the file to write the data.
f.write(data) # Write the new Unicode data to the file
f.close() #close the file
f.close() #make sure the file is closed (sometimes it seems that this fails in Windows.)
a1 += 1 #advances the integer, and then return to the top of the loop
This is an example of writing to a file in ASCII. You need to open the file in byte mode, and using the .encode method for strings is a convenient way to get the end result you want.
s = '12345'
ascii = s.encode('ascii')
with open('somefile', 'wb') as f:
f.write(ascii)
You can obviously also open in rb+ (read and write byte mode) in your case if the file already exists.
with open('somefile', 'rb+') as f:
existing = f.read()
f.write(b'ascii without encoding!')
You can also just pass string literals with the b prefix, and they will be encoded with ascii as shown in the second example.
First off, here's the code. (Still new in function creating)
Function Testing!!
def UserInfo(name, age, birth):
"""Read this by doing UserInfo__doc__"""
print("Name:",name)
print("Age:",age)
print("Birth:",birth)
return
n_input=input("Name?>> ")
a_input=int(input("Age?>> "))
b_input=input("Birth date?(MM DD YYYY)>> ")
UserInfo(n_input, a_input, b_input)
CodeOutput
('name:', 'Jaymz')
('age:', 25)
('birth:', '02 26 1991')
The int portion of the code outputs no " ' " (which I knew) but still with "()" and ","...
The string portion outputs all the stuff I don't want surrounding my output...
How would you get rid of that in your code?(I learn by seeing other code first on how people do it)
ps. Brainfart?.... Do I have to do a "format" on the output code? or is format only for numbers?
you get this output because you're using python 2.x. Python 2 thinks you're printing a tuple. Python 3 would issue what you want.
As jojonas suggested, using from __future__ import print_function also works for all versions. You're not able to use print without parentheses after importing that, which is for the best.
But ...
To treat all cases, use format instead (using {} to indicate the location of the string to insert):
def UserInfo(name, age, birth):
"""Read this by doing UserInfo__doc__"""
print("Name: {}".format(name))
print("Age: {}".format(age))
print("Birth: {}".format(birth))
Note: this also works but is not as powerful:
print("Name: "+name) # would need `str` for integer, ex `str(age)`
print("Name: %s" % name) # old-style formatting