does not print into the original file - python

in the last 2 lines the file1 stays blanks even with the write function. the rest of the code works flawlessly
def modQuantity(filepath: str,):
model = input("Model: ")
size = input("size")
newquantity = input("New Quantity: ")
file = open(filepath, 'r')
tempfile = open(filepath+"temp", 'w')
for line in file:
sep = line.split()
if sep[0] == model and sep[1] == size:
tempfile.write(f"{sep[0]} {sep[1]} {newquantity}\n")
else:
tempfile.write(f"{line}")
tempfile.close()
file.close()
tempfile1 = open(filepath+"temp", 'r')
file1 = open(filepath, 'w')
for line1 in tempfile1:
file1.write(f"{line1}")

You didn't close the file so it hadn't chance to flush the content. You can use that method by yourself or close the file.
I recommend to use contextmanager so you can be sure file is flushed and closed:
with open(filepath, 'w') as file1:
for line1 in tempfile1:
file1.write(f"{line1}")

Related

I tend to create a new file by reading from another one, but when I try use this file, the sys returns:No such file or directory: 'new_text_file.txt'

text_list = []
with open("word5Dict.txt", "r") as f:
for line in f:
for word in line.split("#"):
if word != "\n" :
text_list.append(word)
f.close()
new_file = open("new_text_file", "w")
for word in text_list:
new_file.write(word)
new_file.write("\n")
class ScrabbleDict:
def __init__(self, size, filename):
self.dictionary = {}
with open(filename,"r") as f:
for line in f:
key = line.replace("\n","")
if len(key) == size:
self.dictionary[key] = key
I tend to create a new file by reading from another one, but when I try to use this file in the class I created, the sys returns: No such file or directory: 'new_text_file.txt'
new_file = open("new_text_file", "w")
does not automatically add the file extension. Use
new_file = open("new_text_file.txt", "w")
instead.

How to read a file and print it, skipping certain lines in python

I would like to read a file line by line but ignore any that contain a colon (:).
I'm currently opening one file, reading it, and trying to print it before eventually put it into a new file.
def shoppinglist():
infile = open('filename.txt')
contents = infile.readline()
output = open('outputfilename.txt', 'w')
while ":" not in contents:
contents = infile.readline()
else:
contentstr = contents.split()
print(contentstr)
output.write(contents)
infile.close()
output.close()
As it is, one line is repeated over and over and over.
Try:
def shoppinglist():
contents = ""
with open('filename.txt', 'r') as infile:
for line in infile.readlines():
if ":" not in line:
contents += line
with open('outputfilename.txt', 'w') as output_file:
output_file.write(contents)

Removing complete lines of text in a text file (on Python)

I am working with an output log file that has 12 thousand lines of code, most of which include something that looks like this:
"760.0132 EXP window1: blendMode = 'avg'"
My goal is to entirely remove any line that has "EXP window1: blendMode = 'avg'". I can remove that text bit from all of the lines where it is found, but not the number. This is the code I have used to delete the text bits (borrowed from another stack overflow question/answer):
infile = "01_Day1_run1.txt"
outfile = "01_Day1_run1_cleaned.txt"
delete_list = [" EXP window1: blendMode = 'avg'"]
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()
I was hoping that I would be able to add something like
delete_list = ["1**.**** EXP window1: blendMode = 'avg'"]
in order to delete any number that includes all of the text, and also any number in that line, but it does not seem to work. Any advice on how to best clean up the log file would be greatly appreciated.
Thanks very much,
Simon
Why do you want to do this using Python? You can do this with a simple grep -v or findstr /V, as in following example:
Prompt>grep -v "blendmode" input.txt >output.txt
infile = "01_Day1_run1.txt"
outfile = "01_Day1_run1_cleaned.txt"
delete_list = [" EXP window1: blendMode = 'avg'"]
fin = open(infile)
fout = open(outfile, "a")
for line in fin:
for word in delete_list:
if word in line:
wordCheck = False
break
else:
wordCheck = True
if wordCheck:
fout.write(line)
fin.close()
fout.close()
Maybe cleaner:
with open("01_Day1_run1.txt", "r") as infile, open("01_Day1_run1_cleaned.txt", "a") as outfile:
for line in infile:
if not any(filter in line for filter in delete_list ):
outfile.write(line)
infile = "01_Day1_run1.txt"
outfile = "01_Day1_run1_cleaned.txt"
delete_string = "EXP window1: blendMode = 'avg'"
fin = open(infile)
fout = open(outfile, "a")
for line in fin.readLines():
if delete_list not in line:
fout.write(line)
fin.close()
fout.close()

Unable to get text file output in python 2.7

I have taken input from Numbers.txt file and want to write output in out.txt file,
can anyone guide what is going wrong.
import num2word_EN as s
text = open("C:\\Users\\eanaaks\\Desktop\\Python Practice Program\\Numbers.txt","r")
outfile = open("C:\\Users\\eanaaks\\Desktop\\Python Practice Program\\out.txt", "w")
for line in text:
line = line.rstrip()
num = int(line)
print line
x = s.to_card(num)
print (x)
outfile.write("%s\n"%(line));
outfile.close()
text.close()
Here's an improved version of your code:
import num2word_EN as s
input_file = 'C:\Users\eanaaks\Desktop\Python Practice Program\Numbers.txt'
output_file = 'C:\Users\eanaaks\Desktop\Python Practice Program\out.txt'
with open(input_file, 'r') as fin
with open(output_file, 'w') as fout:
for line in fin:
num = int(line)
print(line)
x = s.to_card(num)
print(x)
# What's the data type of x? int? string?
# This will write the original data and the processed data separated by tab.
fout.write('%s\t%s\n' % (line.rstrip(), x));

File Function in python 3

Hi im new at python(i have been learning it for like 3 days) and for your help will be thankful.
So i made this function which u see below , created 2.txt documents called oldfile,newfile. To the oldfile i wrote 64 characters(like "asasdasffafdsfsfgsgsdgS"). The function should open both files and write to the new file 50 characters from the new file but when i press start in pyscripter the code works but it doesnt do anything(It wont write anything to the newfile.txt).
def copy_file(oldfile, newfile):
infile = open(oldfile, 'r')
outfile = open(newfile, 'w')
while True:
text = infile.read(50)
if text == "":
break
outfile.write(text)
infile.close()
outfile.close()
return
you need to call your function:
def copy_file(oldfile, newfile):
infile = open(oldfile, 'r')
outfile = open(newfile, 'w')
while True:
text = infile.read(50)
if text == "":
break
outfile.write(text)
infile.close()
outfile.close()
return
copy_file('old_file_name_path', 'new_file_name_path') # call your function with path of file here

Categories