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?
Related
I'm trying to create_python_script function that creates a new python script in the current working directory, adds the line of comments to it declared by the 'comments' variable, and returns the size of the new file. The output I get is 0 but should be 31. Not sure what I'm doing wrong.
import os
def create_python_script(filename):
comments = "# Start of a new Python program"
with open("program.py", "w") as file:
filesize = os.path.getsize("/home/program.py")
return(filesize)
print(create_python_script("program.py"))
You forgot to actually write to the file, so it won't contain anything. Another important thing to keep in mind, is that the file is closed automatically after the with statement. In other words: nothing is written to the file until the with statement ends, so the file size is still zero in your program.
This should work:
import os
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, "w") as f:
f.write(comments)
filesize = os.path.getsize(filename)
return(filesize)
print(create_python_script("program.py"))
Note that the input argument was unused previously and has now been changed.
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, 'w') as file:
filesize = file.write(comments)
return(filesize)
print(create_python_script("program.py"))
There is a rogue indent in the exercise:
import os
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, "a") as newprogram:
newprogram.write(comments)
filesize = os.path.getsize(filename)
return(filesize)
print(create_python_script("program.py"))
It should be:
import os
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, "a") as newprogram:
newprogram.write(comments)
filesize = os.path.getsize(filename) #Error over here
return(filesize)
print(create_python_script("program.py"))
I just finished myself.
I have the following code that extracts needed data from a xml file. I can save it to terminal, and open it with no problem. I am in trouble inserting column names to the txt file, however. I have been searching the answer but found no right solution. Would anyone help me here? Thank you!!
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
orig_stdout = sys.stdout
sys.stdout = f
for program in root.findall('program'):
programID = program.find('programID')
season = program.find('season')
print programID, season
sys.stdout = orig_stdout
f.close()
The way to write data to a file in Python is to call .write(content) on the file object, not to redirect stdout to it.
Instead of all your lines messing with sys.stdout, try this:
f = open("file.txt", "w") # Open the file in (w)rite mode
f.write("programID,Season\n") # Header line
for program in root.findall("program"):
programID = program.find("programID").text
season = program.find("season").text
line = programID + "," + season + "\n"
f.write(line)
f.close() # Outside the loop
There are better ways to make the string for line, but we don't need to worry about those at the moment.
When I look at what it wrote it's always double. For example if I write 'dog' ill get 'dogdog'. Why?
Reading and writing to file, filename taken from command line arguments:
from sys import argv
script,text=argv
def reading(f):
print f.read()
def writing(f):
print f.write(line)
filename=open(text)
#opening file
reading(filename)
filename.close()
filename=open(text,'w')
line=raw_input()
filename.write(line)
writing(filename)
filename.close()
As I said the output I am getting is the double value of what input I am giving.
You are getting double value because you are writing two times
1) From the Function call
def writing(f):
print f.write(line)
2) By writing in file using filename.write(line)
Use this code:
from sys import argv
script,text=argv
def reading(f):
print f.read()
def writing(f):
print f.write(line)
filename=open(text,'w')
line=raw_input()
writing(filename)
filename.close()
And also no need to close file two times, once you finished all the read and write operations then just close it.
If you want to display each line and then write a new line, you should probably just read the entire file first, and then loop over the lines when writing new content.
Here's how you can do it. When you use with open(), you don't have to close() the file, since that's done automatically.
from sys import argv
filename = argv[1]
# first read the file content
with open(filename, 'r') as fp:
lines = fp.readlines()
# `lines` is now a list of strings.
# then open the file for writing.
# This will empty the file so we can write from the start.
with open(filename, 'w') as fp:
# by using enumerate, we can get the line numbers as well.
for index, line in enumerate(lines, 1):
print 'line %d of %d:\n%s' % (index, len(lines), line.rstrip())
new_line = raw_input()
fp.write(new_line + '\n')
I'm a beginner and learning Python.
I've created this as to practice function writing. I understand it isn't necessary to write it like so.
My problem is that the out_file data gets deleted, and not replaced with the intended in_file data.
from sys import argv
script, in_file, out_file = argv
print "Copying from filename '%s' to filename '%s'" % (in_file, out_file)
print "The input data reads as: \n"
in_file = open(in_file)
print in_file.read()
print "The file to be overwritten originally reads as \n"
out_file = open(out_file, 'w+')
print out_file.read()
print "Now, to practice function writing, we will use one to overwrite:"
def overwrite():
out_file.write(in_file.read())
print out_file.read()
print "The overwritten file now reads as:\n"
overwrite()
Thus the output of >python ex20.py cat.txt dog.txt is: (where dog.txt = "dogs are the best", and cats.txt = "cats are the best")
Copying from filename 'cat' to filename 'dog'
The input data reads as:
cats are the best
The file to be overwritten originally reads as
Now, to practice function writing, we will use one to overwrite:
The overwritten file now reads as:
What I would like the final code to execute is read a string of names in a text document named, 'names.txt'. Then tell the program to calculate how many names there are in that file and display the amount of names. The code I have so far was meant to display the sum of the numbers in a text file, but it was close enough to the program I need now that I think I may be able to rework it to gather the amount of strings/names and display that instead of the sum.
Here is the code so far:
def main():
#initialize an accumulator.
total = 0.0
try:
# Open the file.
myfile = open('names.txt', 'r')
# Read and display the file's contents.
for line in myfile:
amount = float(line)
total += amount
# Close the file.
myfile.close()
except IOError:
print('An error occured trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except:
print('An error occured.')
# Call the main function.
main()
I am still really new to Python programming so please don't be too harsh on me. If anyone can figure out how to rework this to display the amount of numbers/names instead of the sum of numbers. I would greatly appreciate it. If this program cannot be reworked, I would be happy to settle for a new solution.
Edit: This it an example of what the 'names.txt' will look like:
john
mary
paul
ann
If you just want to count the lines in the file
# Open the file.
myfile = open('names.txt', 'r')
#Count the lines in the file
totalLines = len(myfile.readlines()):
# Close the file.
myfile.close()
fh = open("file","r")
print "%d lines"%len(fh.readlines())
fh.close()
or you could do
fh=open("file","r")
print "%d words"%len(fh.read().split())
fh.close()
All this is readily available information that is not hard to find if you put forth some effort...just getting the answers usually results in flunked classes...
Considering the names in your text files are delimited by line.
myfile = open('names.txt', 'r')
lstLines = myfile.read().split('\n')
dict((name,lstLines.count(name)) for name in lstLines)
This creates a dictionary of each name having its number of occurrence.
To search for the occurrence of perticular name such as 'name1' in the list
lstLines.count('name1')
Assuming names are splitted using whitespaces :
def main():
#initialize an accumulator.
total = 0.0
try:
# Open the file.
myfile = open('names.txt', 'r')
# Read and display the file's contents.
for line in myfile:
words = line.split()
total += len(words)
# Close the file.
myfile.close()
except IOError:
print('An error occured trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except:
print('An error occured.')
# Call the main function.
main()
Use with statement to open a file. It will close the file properly even if an exception occurred. You can omit the file mode, it is default.
If each name is on its own line and there are no duplicates:
with open('names.txt') as f:
number_of_nonblank_lines = sum(1 for line in f if line.strip())
name_count = number_of_nonblank_lines
The task is very simple. Start with a new code to avoid accumulating unused/invalid for the problem code.
If all you need is to count lines in a file (like wc -l command) then you could use .count('\n') method:
#!/usr/bin/env python
import sys
from functools import partial
read_chunk = partial(sys.stdin.read, 1 << 15) # or any text file instead of stdin
print(sum(chunk.count('\n') for chunk in iter(read_chunk, '')))
See also, Why is reading lines from stdin much slower in C++ than Python?