Printing output to file with Python - python-3.x

I am trying to create a script that takes a file as input, looks up all the email addresses, and writes them to a designated file.
based on other similar questions, i have ended up with this:
import re
Input = open("inputdata.txt", "r")
regex = re.compile("\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b")
Logfile = "Result.txt"
for line in Input:
query = regex.findall(line)
for line in query:
print >>Logfile, query
what am i doing wrong? this outputs nothing.
i am guessing the main problem is "for line in query:", which i have tried changing without any luck.
Cheers!
Edit: i have changed the script as suggested below, with "print (query)" instead.
i still do not get any output.
current script is:
import re
Input = open("Inputdata.txt", "r")
regex = re.compile("\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b")
# logfile = "Result.txt"
for line in Input:
query = regex.findall(line)
for line in query:
with open("Result.txt", "a") as logfile:
logfile.write(line)
It outputs nothing, and tells me: " NameError: name "logfile" not defined".
what causes this, and is this the reason there is no output?

Your Logfile variable is just the name of a file, not an actual file object. Also, you should use with to automatically close the file when you are done. Try this:
with open("Result.txt", "a") as logfile:
print >>logfile, "hello world"
print >>logfile, "another line"
But note that in Python 3.x, the syntax is different, as print is no longer a statement but a function:
with open("Result.txt", "a") as logfile:
print("hello world", file=logfile)
print("another line", file=logfile)
Thus, instead of redirecting print, the best choice might be to write to the file directly:
with open("Result.txt", "a") as logfile:
logfile.write("hello world\n")
logfile.write("another line\n")

I don't think, with print you can write to a file without redirecting the output to a file. The way you have used the print, I guess, you want output redirection only.
Let's say your python script is in a file test.py.
replace the line:
print >>Logfile, query
with just:
print query
And from a terminal/cmd, run the script like this:
python test.py >> Result.txt
This is called output redirection.

Related

to print the next line using pythons loop

i matched a line using regex and now i wanna to print the line next to all the matched line.
import re
file = open(input("Input-file name : ") , "r")
fi = file.readlines()
f=file.readline()
pat=r'^[^\n(E|P):]:\s[EXINTF_DATA\d]\d'
for line in fi:
if re.match(r'^[^\n(E|P):]:\s[EXINTF_DATA\d]\d',line):
print(line.strip())#all the 'Startpoint:'s from the file is getting printed
s=line.strip()
for s in range(len(fi)-1):
if 'input port clocked by CLK' in fi:
print(s.strip())
i also tried last for loop part like this,
for s in range(len(fi)-1):
l=line.startswith('input port clocked by CLK')
print(l)#but this loop was running continoulsy
am trying to print till the string found after printing the next line. am also attaching my text file and how it looks like
am a very beginner in python. can someone help me on this, please.

sed gives unknown command error: char 1: unknown command: `''

i am trying to use sed to do some text processing in a file called host
cluster_ip = "10.223.10.21"
srv_domain = "service_domain.svc"
cmd = f"'/^.*{srv_domain}/!p;$a'{cluster_ip}'\t{srv_domain}'"
Then I am calling it like this
subprocess.call(["/usr/bin/sed", "-i", "-ne", cmd, "host"])
But i am getting this error:
/usr/bin/sed: -e expression #1, char 1: unknown command: `''
Could someone please explain me what am I doing wrong?
Thank You
I also tried using fileinput but i am unable to print print(f"{cluster_ip}\t{srv_domain}\n") to the file instead this is going to the console.
cluster_ip = "123.234.45.5"
srv_domain = "service_domain.svc"
def main():
pattern = '^.*service_domain.svc'
filename = "host1"
matched = re.compile(pattern).search
with fileinput.FileInput(filename, inplace=1) as file:
for line in file:
if not matched(line): # save lines that do not match
print(line, end='') # this goes to filename due to inplace=1
# this is getting printed in console
print(f"{cluster_ip}\t{srv_domain}\n")
main()
I suppose you want to remove the first line and add a last line. You don't need to protect arguments, it's already done by the subprocess module. so you're getting the quotes literally.
quickfix:
cmd = f"/^.*{srv_domain}/!p;$a{cluster_ip}\t{srv_domain}"
better: learn to use python to avoid calling sed in your script and make them complex and non portable. You don't even need regexes here, just substring search (which could be improved with regexes to avoid substring match but the problem is already present in the original expression)
First read your file, drop the line where srv_domain is defined, and add your last line.
Something like this, using a temporary file to hold the modified contents, then overwriting it:
with open("hosts") as fr,open("hosts2","w") as fw:
for line in fr:
if not srv_domain in line:
fw.write(line)
fw.write(f"{cluster_ip}\t{srv_domain}\n")
os.remove("hosts")
os.rename("hosts2","hosts")

Content of file not printing

I am a beginner, learning programming using python 3.7. I am running a basic program to read content of a file after writing on it. But the print function won't print out the content of the file on the terminal. Can you please correct what mistake I am making here:
spam = input("What file would you like to open. Type the name below\n>>>")
# for the file name I type example.txt
work = open(spam, "r+")
work.write(input("Now write something on the file here\n>>"))
x = work.read()
print(x)
work.close()
After the write() completes, the file's object index needs to be moved to the beginning of the file
add work.seek(0) before the read() operation
spam = input("What file would you like to open. Type the name below\n>>>")
# for the file name I type example.txt
work = open(spam, "r+")
work.write(input("Now write something on the file here\n>>"))
work.seek(0)
x = work.read()
print(x)
work.close()
You can't actually read your spam variable since it is not a file.
Instead:
work = open("NewFile.txt", "w")
work.write(spam)
work.close()

Python3 : Using input() how to Read Multiple Lines from pipe (stdin)?

im just curious while learning python3 and didn't found any good explanation on the web, neither here to my question.
reading about input() it says "reads from stdin" so i thought i might experiment and try to use it to read from pipe. and so it does! but only ONE LINE (till EOL). So the next question that came up was
how to read multiple lines from pipe (stdin) using input() ?
i found sys.stdin and used sys.stdin.isatty() to determine if stdin is bound to a tty or not, assuming that if not bound to tty the data is coming from pipe. and so i also found and used successfully sys.stdin.readlines() too to read multiple lines.
but just for my curiosity , is there a way to achieve the same by using the plain input() function ?? so far i didn't found something "to test" if stdin contains more lines without blocking my program.
sorry if all this makes no sense to you.
this is my experimenting code so far without input():
import sys
if sys.stdin.isatty(): # is this a keyboard?
print( "\n\nSorry! i only take input from pipe. "
"not from a keyboard or tty!\n"
"for example:\n$ echo 'hello world' | python3 stdin.py"
""
""
)
else:
print ( "reading from stdin via pipe : \n ")
for line in sys.stdin.readlines():
print(line, end="")
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can these two lines be replaced with
# some construction using plain old input() ?
You can iterate over lines in stdin like any other iterable object:
for line in sys.stdin:
# do something
If you want to read the entire thing into one string, use:
s = sys.stdin.read()
Note that iterating over s would then return one character at a time.
Note that it won't read until there is an EOF terminating stdin.
if you just want to use input() to access lines of the stdin:
print(input()) #prints line 1
print(input()) #prints next line
but lets say you only wanted to access the second line:
input() #accesses the first line
print(input()) #prints second line
Lets say you wanted to take the second line and create an array:
stdin:
10
64630 11735 14216 99233 14470 4978 73429 38120 51135 67060
input()
values = list(map(int, input().split(' ')))
values will equal [64630, 11735, 14216, 99233, 14470, 4978, 73429, 38120, 51135, 67060]

User input after file input in Python?

First year Comp Sci student here.
I have an assignment that is asking us to make a simple game using Python, which takes an input file to create the game-world (2D grid). You're then supposed to give movement commands via user input afterwards. My program reads the input file one line at a time to create the world using:
def getFile():
try:
line = input()
except EOFError:
line = EOF
return line
...after which it creates a list to represent the line, with each member being a character in the line, and then creates a list containing each of these lists (amounting to a grid with row and column coordinates).
The thing is, I later need to take input in order to move the character, and I can't do this because it still wants to read the file input, and the last line from the file is an EOF character, causing an error. Specifically the "EOF when reading a line" error.
How can I get around this?
Sounds like you are reading the file directly from stdin -- something like:
python3 my_game.py < game_world.txt
Instead, you need to pass the file name as an argument to your program, that way stdin will still be connected to the console:
python3 my_game.py game_world.txt
and then get_file looks more like:
def getFile(file_name):
with open(file_name) as fh:
for line in fh:
return line
File interaction is python3 goes like this:
# the open keyword opens a file in read-only mode by default
f = open("path/to/file.txt")
# read all the lines in the file and return them in a list
lines = f.readlines()
#or iterate them at the same time
for line in f:
#now get each character from each line
for char_in_line in line:
#do something
#close file
f.close()
line terminator for the file is by default \n
If you want something else you pass it as a parameter to the open method (the newline parameter. Default=None='\n'):
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Resources