How to completely delete the first line of a text file? - python

I have a script that outputs a text file (Mod_From_SCRSTXT.txt). I need to delete the first line of that file.
I have tried changing the last line of the find function shown below. The first line still get printed in the new file created even with the changes.
def find(substr, infile, outfile):
with open(infile) as a, open(outfile, 'a') as b:
for line in a:
if substr in line:
b.write(line[1:])
srcn_path1 = input(" Enter Path. Example: U:\...\...\SRCNx\SCRS.TXT\n" +
" Enter SRCS.TXT's Path: ")
print ()
scrNumber1 = input(' Enter SCR number: ')
print ()
def find(substr, infile, outfile):
with open(infile) as a, open(outfile, 'a') as b:
for line in a:
if substr in line:
b.write(line) # or (line + '\n')
# action station:
find(scrNumber1, srcn_path1, 'Mod_From_SCRSTXT.txt')
Actual result:
VSOAU-0004 16999
VSOAU-0004
VSOAU-0004
VSOAU-0004
VSOAU-0004
Expected result:
VSOAU-0004
VSOAU-0004
VSOAU-0004
VSOAU-0004

You'll want to make a minor adjustment:
You can either count the lines in the file:
numberOfLines = 0
for line in file:
numberOfLines += 1
for line in range(1, linesInFile + 1):
Or you can ignore the first line through many different ways, this being a simple one:
ignoredLine = 0
for line in file:
if not ignoredLine:
ignoredLine = 1
else:
#Do stuff with the other lines

import pathlib
import os
import copy
import io
def delete_first_line(read_path):
try:
read_path = pathlib.Path(str(read_path))
write_path = str(copy.copy(read_path)) + ".temp"
while os.path.exists(write_path):
write_path = write_path + ".temp"
with open(read_path , mode = "r") as inf:
with open(write_path, mode="w") as outf:
it_inf = iter(inf)
next(it_inf) # discard first line
for line in it_inf:
print(line, file = outf)
os.remove(read_path)
os.rename(write_path, read_path)
except StopIteration:
with io.StringIO() as string_stream:
print(
"Cannot remove first line from an empty file",
read_path,
file = string_stream,
sep = "\n"
)
msg = string_stream.getvalue()
raise ValueError(msg)
except FileNotFoundError:
with io.StringIO() as string_stream:
print(
"Cannot remove first line from non-existant file",
read_path,
file = string_stream,
sep = "\n"
)
msg = string_stream.getvalue()
raise ValueError(msg)
finally:
pass
return

Related

IF condition is not executing even though string is equal

I have 2 files - file1 and filee2. I want to search a Keyword in file1 and copy the next 2 lines of that keyword in file1 and store in variable. Then search the same keyword in file2 and replace the next 2 lines of the keyword in file2 with the variable.
File1:
file2:
For example I want to find the keyword [default] and copy next 2 lines of [default] then find the [default] in file 2 and replace the next two lines with file1.
Here is some code I quickly wrote.
file1 = open("file1.txt", "r") # opens the files
file2 = open("file2.txt", "r")
file1_contents = [line.replace("\n", "").replace(" ", "")
for line in file1.readlines()] # creates a list of the lines without whitespaces and newlines
file2_contents = [line.replace("\n", "").replace(" ", "")
for line in file2.readlines()]
file1.close() # closes the files
file2.close()
keyword = "[default]" # keyword to find
# trys to find the keyword in the list
try:
file1_index = file1_contents.index(keyword)
file1_vars = [file1_contents[file1_index + 1],
file1_contents[file1_index + 2]] # stores the two variables after the keyword
file2_index = file2_contents.index(keyword)
file2_contents[file2_index + 1] = file1_vars[0] # replaces them in file 2
file2_contents[file2_index + 2] = file1_vars[1]
file2_contents = [line + "\n" for line in file2_contents] # adds newlines
# writes the content back to file 2
with open("file2.txt", "w") as file:
file.writelines(file2_contents)
file.close()
except ValueError:
pass
Here is your code revised to get through the if statements. You need to remove the "\n" from the cont[i].
fn1 = open(r'<path>', 'r')
fn = open(r"<path>", "r")
profile = "[default]"
# read the content of the file line by line
cont = fn.readlines()
cont1 = fn1.readlines()
# print(type(cont[0]))
# print(type(profile))
for i in range(len(cont)):
if profile == (cont[i].replace("\n", "")):
#print("IF is passed")
profile_line1 = cont[i+1]
profile_line2 = cont[i+2]
# fn1.write(profile_line1)
print("profile 1 and 2 is", profile_line1, profile_line2)
else:
pass
for i in range(len(cont1)):
if profile == cont1[i].replace("\n", ""):
fn1_profile_line1 = cont1[i+1]
fn1_profile_line2 = cont1[i+2]
print(fn1_profile_line1)
print(fn1_profile_line2)
# fn1.write(profile_line1)
fn1.replace(cont1[i+1], profile_line1)
fn1.replace(cont1[i+2], profile_line2)
else:
pass
fn.close()
fn1.close()
Written code for this but if condition is not executing even it is True.
fn1 = open(r'<path>', 'r')
fn = open(r"<path>","r")
profile = "[default]"
# read the content of the file line by line
cont = fn.readlines()
cont1 = fn1.readlines()
#print(type(cont[0]))
#print(type(profile))
for i in range(len(cont)):
if str(profile) == (cont[i]):
#print("IF is passed")
profile_line1 = cont[i+1]
profile_line2 = cont[i+2]
#fn1.write(profile_line1)
print("profile 1 and 2 is",profile_line1,profile_line2)
else:
pass
for i in range(len(cont1)):
if str(profile) == str(cont1[i]):
fn1_profile_line1 = cont1[i+1]
fn1_profile_line2 = cont1[i+2]
print(fn1_profile_line1)
print(fn1_profile_line2)
#fn1.write(profile_line1)
fn1.replace(cont1[i+1], profile_line1)
fn1.replace(cont1[i+2], profile_line2)
else:
pass
fn.close()
fn1.close()

How can I raise in python specific ValueError?

I have to raise ValueError('Invalid file name') if my infile or outfile or the two of them is empty
this is the code in python:
def get_x_freqs(infile, outfile, x):
# Write the rest of the code for question 3 below here.
f =None
try:
f=open(infile, "r")
if infile=='':
raise ValueError('Invalid file name')
else:
d={}
for line in f:
element = line.split()
for word in element:
d[word]=d.get(word,0)+1
try:
f=open(outfile, "w")
if outfile=='':
raise ValueError('Invalid file name')
else:
sorted_elements = sorted(d.keys(), key=d.get, reverse=True)
for e in sorted_elements[:x]:
print(e, ':', d[e])
finally:
if f!= None:
f.close()
in_filename = 'C:\\Users\\shirl\\Desktop\\מדעים להייטק\\פיתון\\Exercises\\ex.5\\q3.txt'
out_filename = 'C:\\Users\\shirl\\Desktop\\מדעים להייטק\\פיתון\\Exercises\\ex.5\\q3_out.txt'
get_x_freqs(in_filename, out_filename, 3)
Your try-except blocks should more look like this:
try:
f=open(infile, "r")
d = {}
for line in f:
element = line.split()
for word in element:
d[word] = d.get(word, 0) + 1
except:
raise ValueError('Invalid file name')

reading and deleting lines in python

I am trying to read all the lines in a specific file, and it prints the number of the line as an index.
What I am trying to do is to delete the line by inputting the number of the line by the user.
As far as it is now, it prints all the lines with the number of that line, but when I enter the number of the line to be deleted, it's not deleted.
This is the code of the delete function:
def deleteorders ():
index = 0
fh = open ('orders.txt', 'r')
lines = fh.readlines()
for line in lines:
lines = fh.readlines()
index = index+1
print (str(index) + ' ' + line)
try:
indexinp = int(input('Enter the number of the order to be deleted, or "B" to go back: '))
if indexinp == 'B':
return
else:
del line[indexinp]
print (line)
fh = open ('orders.txt', 'w')
fh.writelines(line)
fh.close()
except:
print ('The entered number is not in the range')
return
This should work (you'll need to add the error handling back in):
lines = enumerate(open('orders.txt'))
for i, line in lines:
print i, line
i = int(input(">"))
open('orders.txt', 'w').write(''.join((v for k, v in lines if k != i)))

counting the lines and extract the floating point values and compute the average of the values

So i need to write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:X-DSPAM-Confidence: 0.8475
I am stuck in getting the sum of the extracted values and counting the lines and printing to show the user.
out_number = 'X-DSPAM-Confidence: 0.8475'
Num = 0.0
flag = 0
fileList = list()
fname = input('Enter the file name')
try:
fhand = open(fname)
except:
print('file cannot be opened:',fname)
for line in fhand:
fileList = line.split()
print(fileList)
for line in fileList:
if flag == 0:
pos = out_number.find(':')
Num = out_number[pos + 2:]
print (float(Num))
You have an example line in your code, and when you look through each line in your file, you compute the number in your example line, not in the line from the file.
So, here's what I would do:
import os
import sys
fname = input('Enter the file name: ')
if not os.path.isfile(fname):
print('file cannot be opened:', fname)
sys.exit(1)
prefix = 'X-DSPAM-Confidence: '
numbers = []
with open(fname) as infile:
for line in infile:
if not line.startswith(prefix): continue
num = float(line.split(":",1)[1])
print("found:", num)
numbers.append(num)
# now, `numbers` contains all the floating point numbers from the file
average = sum(numbers)/len(numbers)
But we can make it more efficient:
import os
import sys
fname = input('Enter the file name: ')
if not os.path.isfile(fname):
print('file cannot be opened:', fname)
sys.exit(1)
prefix = 'X-DSPAM-Confidence: '
tot = 0
count = 0
with open(fname) as infile:
for line in infile:
if not line.startswith(prefix): continue
num = line.split(":",1)[1]
tot += num
count += 1
print("The average is:", tot/count)
try this
import re
pattern = re.compile("X-DSPAM-Confidence:\s(\d+.\d+)")
sum = 0.0
count = 0
fPath = input("file path: ")
with open('fPath', 'r') as f:
for line in f:
match = pattern.match(line)
if match is not None:
lineValue = match.group(1)
sum += float(lineValue)
count += 1
print ("The average is:", sum /count)
fname = input("Enter file name: ")
fh = open(fname)
count=0
x=0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
x=float(line.split(":")[1].rstrip())+x
count=count+1
output=x/count
print("Average spam confidence:",output)

Parsing through newline characters in Python

I am working on a fairly basic encoder/decoder where you can input your own text file (as a string) and your own encoder (also as a string: it must be a text file).
Here is my decoder function:
def cDecode(file_name, encoder='standard_encoder.txt', save_new=True): # does not decode multi-lines correctly -- everything goes on a single line. See next comment
'''Decodes <'file_name'> with the reverse method of <'encoder'>.'''
if type(file_name) != str or type(encoder) != str: raise TypeError("<'file_name'> and <'encoder'> must be of type <'str'>.")
if type(save_new) != bool: raise TypeError("<'save_new'> must be of type <'bool'>.")
if file_name[-4:] != '.txt': file_name += '.txt'
if encoder[-4:] != '.txt': encoder += '.txt'
decoder_set = {}
try:
with open(encoder, 'r') as encoding_file:
for line in encoding_file:
line_parts = line.split(': ')
my_key, my_value = line_parts[1], line_parts[0]
I think the error is in here:
I have to remove the '\n' because every character (in the decoding file) is on a new line, like such: 'A: Ð'.
if '\n' in my_key:
loc = my_key.find('\n') # this may be the cause of the single-line of the decoding.
my_key = my_key[:loc] + my_key[loc + 1:]
decoder_set[my_key] = my_value
encoding_file.close()
except IOError:
encoder = 'standard_encoder.txt'
with open(encoder, 'r') as encoding_file:
for line in encoding_file:
line_parts = line.split(': ')
my_key, my_value = line_parts[1], line_parts[0]
# every key has a new line character automatically because it's on a different line
if '\n' in my_key:
loc = my_key.find('\n')
my_key = my_key[:loc] + my_key[loc + 1:]
decoder_set[my_key] = my_value
encoding_file.close()
decodingKeys = decoder_set.keys()
Here is the rest of the function:
if save_new:
try:
decoded_file_name = file_name[:-12] + '_decoded' + file_name[-4:]
encoded_file = open(decoded_file_name, 'a+')
with open(file_name, 'r') as my_file:
for line in my_file:
de_line = ''
for char in line:
if char in decodingKeys: de_char = decoder_set[char]
else: de_char = char
de_line += de_char
encoded_file.write(de_line)
except IOError:
raise NameError(file_name + ' was not found. Decoding process terminated.')
else:
try:
import os
encoded_file = file_name[:-12] + '_decoded' + file_name[-4:]
with open(file_name, 'r+') as my_file:
for line in my_file:
de_line = ''
for char in line:
if char in decodingKeys: en_char = decoding_set[char]
else: de_char = char
de_line += de_char
encoded_file.write(de_line)
os.remove(file_name)
os.rename(encoded_file, file_name)
except IOError:
raise NameError(file_name + ' was not found. Decoding process terminated.')
Say I have a multi-line text-file:
This is a test.
As is this one.
Good bye!
When encoded and then decoded afterward, it shows up like this: This is a test.As is this one.Good bye!.
How can I fix this? I'm expecting it to show up like:
This is a test.
As is this one.
Good bye!
Thanks!
Add a '\n' while writing back the line to file:
encoded_file.write(de_line+'\n')

Categories