How to avoid error using the chr function while decoding ASCII? - python

I've worked on a code to "encode" song lyrics pasted into a text file, using the ord function. This is the code below:
import os
filename = os.path.abspath("WeWillRockYou.txt")
out_file = open('WeWillRockYou2.txt', 'w')
readFile = open (filename, 'r')
for line in readFile:
for char in line:
if not char == "\n":
out_file.write(str(ord(char)))
else:
out_file.write(char)
out_file.close()
After, these song lyrics are put into a new text file, but as ASCII. Now I'm attemping to make a code which will "decode" the song lyrics and write them into a new text file as they were originally, however I get an error. The decode code in the one below:
import os
filename = os.path.abspath("WeWillRockYou2.txt")
out_file = open('WeWillRockYou3.txt', 'w')
readFile = open (filename, 'r')
for line in readFile:
for num in line:
if not num == "\n":
out_file.write(int(chr(num)))
else:
out_file.write(char)
out_file.close()
But I get the error:
Traceback (most recent call last):
line 16, in <module>
out_file.write(int(chr(num)))
TypeError: an integer is required
Any help on how to fix this would be greatly appreciated! Thankss!

Related

Python Dictionary Spell Checker, 'TypeError: write() takes no keyword arguments'

I'm using a python dictionary to compare Shakespeares full works and a 10,000 word dictionary, the code should output all words which weren't found in the 10,000 word dictionary to a separate file called 'SpellChecker.txt'. I believe everything in this code is running correctly. I am only coming across one error to do with saving the data to the output file and can't seem to fix it. Any help is appreciated.
Error:
Traceback (most recent call last):
File "/Users/JakeFrench/Desktop/HashTable.py", line 29, in <module>
f1.write(word+'\n', encoding= 'utf-8')
TypeError: write() takes no keyword arguments
import re
import time
start_time = time.time()
f1=open ('SpellChecker.txt', 'w+')
Dictionary = {}
Document = []
with open ('10kWords.txt', encoding= 'utf-8') as f:
for word in f:
Dictionary[word.rstrip()] = 1
with open ('ShakespeareFullWorks.txt', encoding= 'utf-8') as f:
content = f.read().split(" ")
content = [item.lower() for item in content]
content = ' '.join(content)
content = re.findall("\w+", content)
for line in content:
Document.append(line)
for line in content:
for word in line.split():
if word.lower() not in Dictionary:
f1.write(word+'\n', encoding= 'utf-8')
f1.close()
print ("--- %s seconds ---" % (time.time() - start_time))
Just remove the encoding attribute from the write method and insert it in the open function as follows:
f1=open ('SpellChecker.txt', 'w+', encoding='utf-8')
...
f1.write(word+'\n')

Replace a string with another string within a file in Python

You will be provided a file path for input I, a file path for output O, a string S, and a string T.
Read the contents of I, replacing each occurrence of S with T and write the resulting information to file O.
You should replace O if it already exists.
# Get the filepath from the command line
import sys
I= sys.argv[1]
O= sys.argv[2]
S= sys.argv[3]
T= sys.argv[4]
# Your code goes here
# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')
file2.replace(S, T)
file1.close()
file2.close()
file2= open('O', 'r')
print(file2)
Here's the error I keep getting:
Traceback (most recent call last):
File "write-text-file.py", line 15, in
file2.replace(S, T)
AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'
Here is the code (Modified)
# Get the filepath from the command line
import sys
import re
I= sys.argv[1]
O= sys.argv[2]
S= sys.argv[3]
T= sys.argv[4]
# Your code goes here
# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')
data = file1.read()
data = data.replace(S, T)
file2.write(data)
file1.close()
file2.close()
file2= open(O, 'r')
data = file2.read()
print(data)
file2 is a file object not a string, file object's do not have replace method
try
with open(I, 'r') as file1, open(O, 'w') as file2:
for line in file1.readlines():
line=line.replace(S,T)
file2.write(line)

How to implement STDOUT and file write based on parameter input

I have the input file that looks like this (infile.txt):
a x
b y
c z
I want to implement a program that enable user to write to STDOUT or file depending on the command:
python mycode.py infile.txt outfile.txt
Will write to file.
And with this
python mycode.py infile.txt #2nd case
Will write to STDOUT.
I'm stuck with this code:
import sys
import csv
nof_args = len(sys.argv)
infile = sys.argv[1]
print nof_args
outfile = ''
if nof_args == 3:
outfile = sys.argv[2]
# for some reason infile is so large
# so we can't save it to data structure (e.g. list) for further processing
with open(infile, 'rU') as tsvfile:
tabreader = csv.reader(tsvfile, delimiter=' ')
with open(outfile, 'w') as file:
for line in tabreader:
outline = "__".join(line)
# and more processing
if nof_args == 3:
file.write(outline + "\n")
else:
print outline
file.close()
When using 2nd case it produces
Traceback (most recent call last):
File "test.py", line 18, in <module>
with open(outfile, 'w') as file:
IOError: [Errno 2] No such file or directory: ''
What's the better way to implement it?
You can try this:
import sys
if write_to_file:
out = open(file_name, 'w')
else:
out = sys.stdout
# or a one-liner:
# out = open(file_name, 'w') if write_to_file else sys.stdout
for stuff in data:
out.write(stuff)
out.flush() # cannot close stdout
# Python deals with open files automatically
You can also use this instead of out.flush():
try:
out.close()
except AttributeError:
pass
This looks a bit ugly to me, so, flush will be just well.

Error while using '<file>.readlines()' function

The goal was to import the infile, read it, and print only two lines into the outfile.This is the code I had in IDLE:
def main():
infile = open('names.py', "r")
outfile = open('orgnames.py', "w")
for i in range (2):
line = ("names.py".readlines())
print (line[:-1], infile = outfile)
infile.close()
outfile.close()
main()
This is the error message I keep getting:
Traceback (most recent call last):
File "C:/Python33/studentnames6.py", line 11, in <module>
main()
File "C:/Python33/studentnames6.py", line 6, in main
line = ("names.py".readlines())
AttributeError: 'str' object has no attribute 'readlines'
I have used the function readlines in a similar situation before and it had worked fine. I don't understand why it's having an error now, or how to fix it.
The error is because names.py is a string, and not a file object. The following code should work for you:
def main():
infile = open('names.py', "r")
outfile = open('orgnames.py', "w")
# Prints the first two lines in outfile
for line in infile.readlines()[:2]:
outfile.write(line)
infile.close()
outfile.close()
main()

file crawler OSError

I want this to recursively call the next file, listed in a manually inputted file. It is the first word listed in the file.
The current error messege is:
OSError: [Errno 22] Invalid argument: 'file1.txt\n'.
This is my current code:
import os
def crawl(fname):
infile = open(fname, 'r')
if os.stat(fname)[6]==0:
return "Visiting {}".format(fname)
infile.close()
else:
print ("Visiting {}".format(fname))
lines = infile.read().splitlines()
nextfile = lines[0].strip()
for line in lines:
crawl(nextfile)
Try:
import os
def crawl(fname):
with open(fname, "r") as infile:
print("Visiting {}".format(fname))
if os.stat(fname).st_size:
lines = infile.read().splitlines()
for line in lines:
crawl(line)
I'm pretty sure the problem is that you're getting a newline at the end of the filename you are reading from the first file. You can easily fix it, by using the strip method to remove the newline:
nextfile = lines[0].strip()

Categories