I have the following python code, its working fine with python 2.7, but I want to run it on python 2.5.
I am new to Python, I tried to change the script multiple times, but i always I got syntax error. The code below throws a SyntaxError: Invalid syntax:
#!/usr/bin/env python
import sys
import re
file = sys.argv[1]
exp = sys.argv[2]
print file
print exp
with open (file, "r") as myfile:
data=myfile.read()
p = re.compile(exp)
matches = p.findall(data)
for match in matches:
print " ".join("{0:02x}".format(ord(c)) for c in match)
Python 2.5 doesn't support the with statement yet.
To use it in Python 2.5, you'll have to import it from __future__:
## This shall be at the very top of your script ##
from __future__ import with_statement
Or, as in the previous versions, you can do the procedure manually:
myfile = open(file)
try:
data = myfile.read()
#some other things
finally:
myfile.close()
Hope it helps!
Python 2.5 does not have the with code block support.
Do this instead:
myfile = open(file, "r")
try:
data = myfile.read()
p = re.compile(exp)
matches = p.findall(data)
for match in matches:
print " ".join("{0:02x}".format(ord(c)) for c in match)
finally:
myfile.close()
note: you should not use file as the name of your file, it is an internal Python name, and it shadows the built in.
Related
After a few weeks of reading Learn Python The Hard Way, I want to try to create a small program to read [text file contain hex] and write another file [as decimal]. I expect after type the command-line python convert_hex.py hex.txt, Python will create a new file called hex_1.txt.
#this is content from hex.txt
0x5B03FA01
0x42018360
0x9FF943B3
this is what I expected my python to deliver output
#this is content from hex_1.txt
1526987265
1107395424
2683913139
After 3 hour of trial and error. I can see a result in the way I want. The code is follow;
from sys import argv
from os.path import exists
def hex2dec (hex):
result_dec = int(hex, 0)
return result_dec
script, from_file = argv
to_file = from_file[:len(from_file)-4] + "_1.txt"
out_file = open(to_file, 'w').close()
with open(from_file) as in_file:
lines = in_file.read().splitlines()
for i in lines:
converted = str(hex2dec (i))
out_file = open(to_file, 'a+')
out_file.write(converted + "\n")
out_file.close()
print "converted =" + str(converted)
print "done."
But I think there are plenty of area I should study further e.g. bug handling in hex2dec function. Could anyone suggest me what I can study further to improve this code?
I'm writing a program in python and I am having issues getting idle to read my file out. If I use improper syntax it tells me, so it is being read by the compiler but not printing it for the user. Any help would be appreciated. Here is my code.
#! python3.5.2
import sys
if input() == ('im bored'):
print('What season is it?')
if input() == ('summer'):
f = open('callfilesummer.txt', 'r')
You only put file into variable 'f', so you need to read it or work it with someway to show it.
import sys
if input() == ('im bored'):
print('What season is it?')
if input() == ('summer'):
f = open('callfilesummer.txt', 'r')
print f.read()
f.close()
You can find more way how to work with files on this http://www.tutorialspoint.com/python/python_files_io.htm
This doesn't do anything. Maybe take a look at the Python documentation? https://docs.python.org/3/tutorial/inputoutput.html
That's a start.
If you want to display the file, you can very easily iterate over a file in Python like this:
f = open('hurdurr', 'r')
for line in f:
print line
I am trying to read a filename that has a period in it, into this simple program..
files like "test" work, while test.txt fail.
I kinda see why. when I type in "test.txt", only "test" appears.
when I use quotes, I get:
IOError: [Errno 2] No such file or directory: "'test.txt'"
is there a simple way I can read file names that have things like extensions?
#!/usr/bin/python
#File Attributes
fn=input("Enter file Name: ")
print (fn) #added so i know why its failing.
f = open(`fn`,'r')
lines = f.read()
print(lines)
f.close()
Using the with...as method as stated in this post:
What's the advantage of using 'with .. as' statement in Python?
seems to resolve the issue.
Your final code in python3 would look like:
#!/usr/bin/python
#File Attributes
fn = input("Enter file Name: ")
with open(fn, 'r') as f:
lines = f.read()
print(lines)
In python2 *input("")** is replaced by raw_input(""):
#!/usr/bin/python
#File Attributes
fn = raw_input("Enter file Name: ")
with open(fn, 'r') as f:
lines = f.read()
print(lines)
I would do it the following way:
from os.path import dirname
lines = sorted([line.strip().split(" ") for line in open(dirname(__file__) + "/test.txt","r")], key=lambda x: x[1], reverse=True)
print [x[0] for x in lines[:3]]
print [x[0] for x in lines[3:]]
You use the input function, this built_in function need a valid python input, so you can try this:
r'test.txt'
But you have to make sure that the test.txt is a valid path. I just try your code, I just change the open function to:
f = open(fn,'r')
and input like this:
r'C:\Users\Leo\Desktop\test.txt'
it works fine.
it does work if I type this on python shell
>>> f= open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
>>> f.read()
'plpw eeeeplpw eeeeplpw eeee'
>>> f.close()
but if I create a python program, i doesn't work.
import os
f= open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
f.read()
f.close()
i saved this piece of code by using text editor.
if I execute this program in python shell, it shows nothing.
please tell me why..
In the interactive prompt, it automatically prints anything a function call returns. That means the return value of f.read() is printed automatically. This won't happen when you put it in a program however, so you will have to print it yourself to have it show up.
import os
f = open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
print f.read() # use print(f.read()) in Python 3
f.close()
Another suggestion I would make would be to use a with block:
import os
with open(os.path.join(os.getcwd(), 'test1.txt'), 'r') as f:
print f.read()
This means that you won't have to worry about manually closing the file afterwards.
I am trying to create a very simple log parser script in python. Everything is going as planned except the script on the target machine is returning this error (the script works on a unix machine though quite fine):
for name in root.namelist():
Attribute Error: 'str' object has no attribute 'namelist'
Python versions appear to be the same (2.7.3 on both machines). Any ideas?
Script itself:
import zipfile
import os
import re
string1 = "searchstring" # raw_input("usrinput: ")
try:
root = zipfile.ZipFile("/home/testuser/docs/testzip.zip", "r")
except:
root = "testfolder/"
for name in root.namelist():
if name.find(".") > 0:
f = root.open(name)
searchlines = f.readlines()
for i, line in enumerate(searchlines):
regex1 = "(.*)" + re.escape(string1) + "(.*)"
if re.match (regex1, line):
for l in searchlines[i-4:i+4]: print l,
print
This is because root = "testfolder/" it doesn't have any namelist as its attribute.
Type of root is string
Which in turn looking at your code means, root = zipfile.ZipFile("/home/testuser/docs/testzip.zip", "r") generated an exception
in exception block try to use except Exception, ex: and then print ex.message to understand the type of exception being generated
This is because, namelist() is only available for a zipfile, not for a string.
This happens when the zip file cannot be opened. Check the path where the zip file is located.
Try this and see the output:
try:
root = zipfile.ZipFile("/home/testuser/docs/testzip.zip", "r")
except Exception, msg:
print msg
root = "testfolder/"
When I tried with a valid zip file, the program worked fine.