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)
Related
I am trying to get only numbers from a particular row from 10 different text files. As an output, I want those numbers appended as a list. I'm a new learner. I would appreciate your help.
tried this one but not working
import os
import sys,re
line_number=69
path = r'C:\Users\arpan\OneDrive\Desktop\New folder'
for filename in os.listdir(path):
with open(os.path.join(path, filename), 'r') as f:
#print (filename)
file = open(filename)
all_lines_variable = file.readlines()
sys.stdout = open("output", "a") #print output file
print(filename, all_lines_variable[line_number])
sys.stdout.close()
You can try this script, it will extract from all files line number 69 and then appends it to output.txt file:
import os
import re
line_number=69
path = r'C:\Users\arpan\OneDrive\Desktop\New folder'
with open('output.txt', 'w') as f_out:
for file in os.listdir(path):
with open(os.path.join(path, file), 'r') as f_in:
lines = f_in.readlines()
print(' '.join(re.findall(r'\d+', lines[line_number])), file=f_out)
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!
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.
I am quite new to Python and even newer to stdin stdout method. Nevertheless I need to make my script usable for UNIX commands, in order to make it possible for example to process 2 input files at once with my script.
This script works perfectly well with command line arguments:
newlist = []
def f1()
....
def f2(input_file):
vol_id = sys.argv[3]
for line in input_file:
if ... :
line = line.replace('abc','def')
line = line.replace('id', 'id'+vol_id)
....
newlist.append(line)
return newlist
def main():
if len(sys.argv) < 4:
print 'usage: ./myscript.py [file_in... file_out... volume_id]'
sys.exit(1)
else:
filename = sys.argv[1]
filename_out = sys.argv[2]
tree = etree.parse(filename)
extract(tree)
input_file = open(filename, 'rU')
change_class(input_file)
file_new = open(filename_out, 'w')
for x in newlist:
if '\n' in x:
x = x.replace('\n', '')
print>>file_new, x
When I tried to add stdin stdout to it, I first had a problem with reading the same input file first, and for this reason made some chages so that it would be actually open only once. Here is my modified main():
filename = sys.argv[1]
filename_out = sys.argv[2]
if filename == '-':
filename = sys.stdin
else:
input_file = open(filename, 'rU')
if filename_out == '-':
filename_out = sys.stdout
file_new = filename_out
else:
file_new = open(filename_out, 'w')
input_file = open(filename, 'rU')
tree = etree.fromstring(input_file)
extract(tree)
change_class(input_file)
for x in newlist:
if '\n' in x:
x = x.replace('\n', '')
print>>file_new, x
Then I ran my script like this:
./myscript.py - - volumeid < inputfile > outputfile
And I got this error message:
Traceback (most recent call last):
File "./myscript.py", line 191, in <module>
main()
File "./myscript.py", line 175, in main
input_file = open(filename, 'rU')
TypeError: coercing to Unicode: need string or buffer, file found
What am I doing wrong?
You are trying to use an open file object as a filename:
filename = sys.stdin
# ...
input_file = open(filename, 'rU')
You cannot re-read from sys.stdin anyway; you need to read all of the file into memory, then process it twice:
if filename == '-':
input_file = sys.stdin
else:
input_file = open(filename, 'rU')
input_data = input_file.read()
tree = etree.fromstring(input_data)
extract(tree)
change_class(input_data)
mwhere you'll have to alter change_class to handle a string, not an open file object.
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')