How to put all print output from cmd to a txt file? - python

Can you help me identify what's wrong in this code? I want to put all the print output on the cmd to a txt file. This code only puts the last line.
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
for line in fhand:
z = line.decode().strip()
with open('romeo.txt', 'w') as f:
print(z, file=f)

You are creating and writing 'romeo.txt' file for every line of the content. Swap the for loop and the opening file. Something like this:
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
with open('romeo.txt', 'w') as f:
for line in fhand:
z = line.decode().strip()
print(z, file=f)

Related

I need to print the specific part of a line in a txt file

I have this text file that reads ,,Janitors, 3,, ,,Programers, 4,, and ,,Secretaries, 1,, and all of these are on different lines. I need to print out Janitor seperate from the number 3, and this has to work for basicaly any word and number combo. This is the code I came up with and, of course, it doesnt work. It says ,,substring not found,,
File = open("Jobs.txt", "r")
Beg_line = 1
for lines in File:
Line = str(File.readline(Beg_line))
Line = Line.strip('\n')
print(Line[0: Line.index(',')])
Beg_line = Beg_line + 1
File.close()
Try running the following code:
file = open("Jobs.txt", "r")
lines = file.read().split('\n')
for line in lines:
print(line.split(' ')[0])
file.close()
This will give the following output:
Janitors
Programers
Secretaries

Not printing file contents

I'm trying to read and print the contents of a text file, but nothing shows up:
coffee = open('coffeeInventory.txt' , 'r')
coffee.seek(0)
line = coffee.readline()
while line != '':
print(line)
coffee.close()
Thank you for any advice.
Try this:
with open('coffeeInventory.txt') as inf:
for line in inf:
print(line, end='')
readline leaves a newline on the end of the line, so use end='' to prevent print from appending its own newline.
Try this code for each line, please:
file = open('coffeeInventory.txt')
lines = file.readlines()
for line in lines:
print(line)
file.close()

Text in a file replaced by regex. How to write the change into file?

I can change the text in a file line by line, but I don't know how to write the results (changes) into the file.
This is a small part of my file:
<name>2016-09-15_obere-firstalm_gehen-6,5km</name>
<extensions>
<line xmlns="http://www.topografix.com/GPX/gpx_style/0/2">
<color>000000</color>
</line>
</extensions>
<trkseg>
<trkpt lat="47.671193" lon="11.886518">
<ele>1115.6</ele>
<time>2016-09-15T11:57:44Z</time>
</trkpt>
<trkpt lat="47.670686" lon="11.886412">
<ele>1117.6</ele>
<time>2016-09-15T11:58:14Z</time>
</trkpt>
<trkpt lat="47.670821" lon="11.886459">
<ele>1055.6</ele>
<time>2016-09-15T11:58:44Z</time>
</trkpt>
With a Python script I change values of elevations by adding 30.
Example:
Before change:
elevation (ele) 1115.6,
after change:
elevation (ele) 1145.6
#This little Python adds 30 to elevation:
import re
f1 = raw_input("name of your GPX file: ")
f1 = open(f1,'r+')
for line in f1:
res = re.search(r"<(ele)>(.+)</\1>",line)
if res:
number=float(res.group(2))
number_elev=number+30
number_elev=str(number_elev)
ress = re.sub(r"<(ele)>(.+)", r"\2",number_elev)
#print shows correct new values between <ele> and </ele>
print ress + "\n"
###but how to write into the gpx file these changes?
f1.close()
print "OK"
Expected: Write the file with the changed lines.
Actual: I don't know how to write a change by regexp into the file.
Thx in advance for your help.
You'll first need to read all the lines in your file and write each one to the file replacing the ones matching the regex search.
Also since one more <ele>..</ele> tag sequences can be on the same line, you'll need to find all occurrences of those in the line and replace them accordingly.
import re
f1 = raw_input("name of your GPX file: ")
with open(f1,'r') as f:
lines = f.readlines()
with open(f1, 'w') as f:
for line in lines:
ress = line
res = re.findall(r"<(ele)>(.+)</\1>",ress)
if res:
for r in res:
number=float(r[1])
number_elev=number+30
number_elev=str(number_elev)
ress=re.sub(r"<(ele)>{}</(ele)>".format(r[1]), r"<ele>{}</ele>".format(number_elev),string=ress, count=1)
f.write(ress)
Don't try to read and write from/to the same file at the same time. Just create and output file and write to it.
The following code is untested but it should work.
import re
f1 = input("name of your GPX file: ")
input_file = open(f1,'r+')
output_file = open(f1 + '_output', 'w+')
for line in input_file:
res = re.search(r"<(ele)>(.+)</\1>", line)
if res:
number=float(res.group(2))
number_elev=number+30
number_elev=str(number_elev)
line = line.replace(res.group(2), number_elev)
output_file.write(line)
input_file.close()
output_file.close()
print("OK")
You can read the file all at once and apply the regex to the data and write out the modified data to another file as follows:
import re
with open('input-file.xml') as fd:
data = fd.read()
regex = re.compile('(<ele>)([\d.]+)(</ele>)')
while True:
match = regex.search(data)
if not match:
break
new_value = float(match.group(2)) + 30
# <ele>6373.8</ele> becomes </ele>6373.8<ele> so that it doesnt match again
data = regex.sub(r'\g<3>{}\g<1>'.format(new_value), data, count=1)
# undo </ele>...<ele> the tag reversal done inside the while loop
regex = re.compile('(</ele>)([\d.]+)(<ele>)')
data = regex.sub(r'\3\2\1', data)
with open('output-file.xml', 'w') as fd:
fd.write(data)

How to erase line from text file in Python?

I'm trying to make a code to rewrite a specific line from a .txt file.
I can get to write in the line i want, but i can't erase the previous text on the line.
Here is my code:
(i'm trying a couple of things)
def writeline(file,n_line, text):
f=open(file,'r+')
count=0
for line in f:
count=count+1
if count==n_line :
f.write(line.replace(str(line),text))
#f.write('\r'+text)
You can use this code to make a test file for testing:
with open('writetest.txt','w') as f:
f.write('1 \n2 \n3 \n4 \n5')
writeline('writetest.txt',4,'This is the fourth line')
Edit: For Some reason, if i use 'if count==5:' the code compiles ok (even if it doen't erase the previous text), but if i do 'if count==n_line: ', the file ends up with a lot of garbage.
The Answers work, but i would like to know what are the problems with my code, and why i can't read and write. Thanks!
You are reading from the file and also writing to it. Don't do that. Instead, you should write to a NamedTemporaryFile and then rename it over the original file after you finish writing and close it.
Or if the size of the file is guaranteed to be small, you can use readlines() to read all of it, then close the file, modify the line you want, and write it back out:
def editline(file,n_line,text):
with open(file) as infile:
lines = infile.readlines()
lines[n_line] = text+' \n'
with open(file, 'w') as outfile:
outfile.writelines(lines)
Use temporary file:
import os
import shutil
def writeline(filename, n_line, text):
tmp_filename = filename + ".tmp"
count = 0
with open(tmp_filename, 'wt') as tmp:
with open(filename, 'rt') as src:
for line in src:
count += 1
if count == n_line:
line = line.replace(str(line), text + '\n')
tmp.write(line)
shutil.copy(tmp_filename, filename)
os.remove(tmp_filename)
def create_test(fname):
with open(fname,'w') as f:
f.write('1 \n2 \n3 \n4 \n5')
if __name__ == "__main__":
create_test('writetest.txt')
writeline('writetest.txt', 4, 'This is the fourth line')

Python How to keep x lines after a regex match

I am pretty new to Python. I have a bunch of articles in a txt files, all ending with the mention "Copyright". After this pattern is match I d like to keep a certain nber, x, of lines and copy them in another file.
I have tried the following code and a lot of variations (with issue on the index being out of the range) but I have an empty return.
Could you please help me ?
Thanks
with open("ILL 2013.txt",'r') as file:
with open('output.txt','w') as f:
#lines=file.readlines()
#match = re.search('Copyright', lines)
#searchquery="Copyright"
#try:
for line in file:
if re.search("copyright",line):
i=file.index(line)
for iline in range(i,i+2):
f.write(file[iline])
print('done.')
#except:
#print('not in file.')
How about
if re.search("copyright", line):
for _ in range(x):
line = file.readline()
f.write(line)
Sorry for the bad post, here is what I did :
Import modules
from future import division
import re, pprint
def main():
with open("ILL 2013.txt",'r') as file:
with open('output.txt','w') as f:
#try:
for line in file:
if re.search("Copyright",line):
#line = file.readline()
for _ in range(10):
f.write(line)
print('done.')
#except:
#print('not in file.')
if name == "main": main()

Categories

Resources