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

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()

Related

Can't run file with sys.arg[1]

I'm working through https://testdriven.io/developing-an-asynchronous-task-queue-in-python . I've also taken a look at sys.argv[1] meaning in script for clarification on sys.argv
From the former I have:
def save_file(filename, data):
random_str = uuid.uuid4().hex
outfile = f'{filename}_{random_str}.txt'
with open(os.path.join(OUTPUT_DIRECTORY, outfile), 'w') as outfile:
outfile.write(data)
def get_word_counts(filename):
wordcount = collections.Counter()
# get counts
with open(os.path.join(DATA_DIRECTORY, filename), 'r') as f:
for line in f:
wordcount.update(line.split())
for word in set(COMMON_WORDS):
del wordcount[word]
# save file
save_file(filename, json.dumps(dict(wordcount.most_common(20))))
# simulate long-running task
time.sleep(2)
proc = os.getpid()
print(f'Processed {filename} with process id: {proc}')
if __name__ == '__main__':
print(sys.argv, len(sys.argv))
# print(sys.argv[1], len(sys.argv))
get_word_counts(sys.argv[1])
When I run it directly with I get:
$ python tasks.py
['tasks.py'] 1
Traceback (most recent call last):
File "tasks.py", line 46, in <module>
get_word_counts(sys.argv[1])
IndexError: list index out of range
Given that you can see there is only one element in the list, why did the author write the the code in this way?
get_word_counts(sys.argv[1])
Should be
get_word_counts(sys.argv[0])
Indexes start at zero in most languages (including python)

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 avoid error using the chr function while decoding ASCII?

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!

What's Wrong With My Code? (ValueError: I/O operation on closed file)

Can Someone Explain to me what is wrong with my code? I get the following error:
Traceback (most recent call last): File "C:\LineRep.py", line
15, in module:
for line in File2: ValueError: I/O operation on closed file
My Code:
import os, Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dirprompt = tkFileDialog.askopenfilename()
File = open (dirprompt, 'r')
File2 = open (dirprompt + 'temp', 'w')
for line in File:
File2.write(line.replace(',', ' '))
File.close()
File2.close()
names = []
for line in File2:
names.append(line)
print names
You are iterating over File2 after you call File2.close()

Bad file descriptor error

If I try executing the following code
f = file('test','rb')
fout = file('test.out','wb')
for i in range(10):
a = f.read(1)
fout.write(a)
f.close()
f = fout
f.seek(4)
print f.read(4)
Where 'test' is any arbitrary file, I get:
Traceback (most recent call last):
File "testbad.py", line 12, in <module>
print f.read(4)
IOError: [Errno 9] Bad file descriptor
If however, I change just the fout line to use a temporary file:
import tempfile
f = file('test','rb')
fout = tempfile.NamedTemporaryFile()
for i in range(10):
a = f.read(1)
fout.write(a)
f.close()
f = fout
f.seek(4)
print f.read(4)
There are no errors. Does anyone know why this is? I would have expected the first case to work, but I must be doing something wrong.
Thanks in advance for any help!
you've only opened the file fout for writing, not reading. To open for both use
fout = file('test.out','r+b')

Categories