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));
Related
I have a text file with names and results. If the name already exists, only the result should be updated. I tried with this code and many others, but without success.
The content of the text file looks like this:
Ann, 200
Buddy, 10
Mark, 180
Luis, 100
PS: I started 2 weeks ago, so don't judge my bad code.
from os import rename
def updatescore(username, score):
file = open("mynewscores.txt", "r")
new_file = open("mynewscores2.txt", "w")
for line in file:
if username in line:
splitted = line.split(",")
splitted[1] = score
joined = "".join(splitted)
new_file.write(joined)
new_file.write(line)
file.close()
new_file.close()
maks = updatescore("Buddy", "200")
print(maks)
I would suggest reading the csv in as a dictionary and just update the one value.
import csv
d = {}
with open('test.txt', newline='') as f:
reader = csv.reader(f)
for row in reader:
key,value = row
d[key] = value
d['Buddy'] = 200
with open('test2.txt','w', newline='') as f:
writer = csv.writer(f)
for key, value in d.items():
writer.writerow([key,value])
So what needed to be different mostly is that when in your for loop you said to put line in the new text file, but it's never said to Not do that when wanting to replace a score, all that was needed was an else statement below the if statement:
from os import rename
def updatescore(username, score):
file = open("mynewscores.txt", "r")
new_file = open("mynewscores2.txt", "w")
for line in file:
if username in line:
splitted = line.split(",")
splitted[1] = score
print (splitted)
joined = ", ".join(splitted)
print(joined)
new_file.write(joined+'\n')
else:
new_file.write(line)
file.close()
new_file.close()
maks = updatescore("Buddy", "200")
print(maks)
You can try this, add the username if it doesn't exist, else update it.
def updatescore(username, score):
with open("mynewscores.txt", "r+") as file:
line = file.readline()
while line:
if username in line:
file.seek(file.tell() - len(line))
file.write(f"{username}, {score}")
return
line = file.readline()
file.write(f"\n{username}, {score}")
maks = updatescore("Buddy", "300")
maks = updatescore("Mario", "50")
You have new_file.write(joined) inside the if block, which is good, but you also have new_file.write(line) outside the if block.
Outside the if block, it's putting both the original and fixed lines into the file, and since you're using write() instead of writelines() both versions get put on the same line: there's no \n newline character.
You also want to add the comma: joined = ','.join(splitted) since you took the commas out when you used line.split(',')
I got the result you seem to be expecting when I put in both these fixes.
Next time you should include what you are expecting for output and what you're giving as input. It might be helpful if you also include what Error or result you actually got.
Welcome to Python BTW
Removed issues from your code:
def updatescore(username, score):
file = open("mynewscores.txt", "r")
new_file = open("mynewscores2.txt", "w")
for line in file.readlines():
splitted = line.split(",")
if username == splitted[0].strip():
splitted[1] = str(score)
joined = ",".join(splitted)
new_file.write(joined)
else:
new_file.write(line)
file.close()
new_file.close()
I believe this is the simplest/most straightforward way of doing things.
Code:
import csv
def update_score(name: str, score: int) -> None:
with open('../resources/name_data.csv', newline='') as file_obj:
reader = csv.reader(file_obj)
data_dict = dict(curr_row for curr_row in reader)
data_dict[name] = score
with open('../out/name_data_out.csv', 'w', newline='') as file_obj:
writer = csv.writer(file_obj)
writer.writerows(data_dict.items())
update_score('Buddy', 200)
Input file:
Ann,200
Buddy,10
Mark,180
Luis,100
Output file:
Ann,200
Buddy,200
Mark,180
Luis,100
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)
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()
Let's say I have this textfile: date.txt. month|day|year
January|20|2014
February|10|
March|5|2013
I want to put 2012 after February|10|. how can i do that?
You need to read the file into memory, modify the desired line and write back the file.
temp = open('temp', 'wb')
with open('date.txt', 'r') as f:
for line in f:
if line.startswith('February'):
line = line.strip() + '2012\n'
temp.write(line)
temp.close()
shutils.move('temp', 'data.txt')
If you don't want to use a temporary file:
with open('date.txt', 'r+') as f: #r+ does the work of rw
lines = f.readlines()
for i, line in enumerate(lines):
if line.startswith('February'):
lines[i] = lines[i].strip() + '2012\n'
f.seek(0)
for line in lines:
f.write(line)
You can use the csv module, for example:
import csv
data = [
"January|20|2014",
"February|10|",
"March|5|2013"
]
reader = csv.reader(data, delimiter="|")
for line in reader:
line = [i if i != "" else "2012" for i in line]
print(line)
Please note: csv.reader() take as argument any iterable object. So, you can easily pass it a file object
I have txt with a number of lines (x#y). Each file has two parts (x, y) separated by a particular symbol (#). How would a python script that reads each line in a txt and adds a new line under each existing line, where the order of the two parts (x#y) is inverted (y#x).
What I'm trying to do presented as input/output:
INPUT:
x1#y1
x2#y2
x3#y3
OUTPUT:
x1#y1
y1#x1
x2#y2
y2#x2
x3#y3
y3#x3
How can this be done with python?
Here's one way:
infilename = 'in.dat'
outfilename = 'out.dat'
sep = '#'
with open(infilename) as infile, open(outfilename,'w') as outfile:
for line in infile:
split = line.strip().partition(sep)
outfile.write(line)
outfile.write(''.join(reversed(split)) + '\n')
and then
~/coding$ cat in.dat
x1#y1
x2#y2
x3#y3
~/coding$ python inverter.py
~/coding$ cat out.dat
x1#y1
y1#x1
x2#y2
y2#x2
x3#y3
y3#x3
Assumes the name of your file is bar.txt, and that you want to write it back to bar.txt. It also does no error checking nor cares about memory usage.
if __name__ == "__main__":
myfile = open("bar.txt", "rb")
lines = myfile.readlines()
myfile.close()
myfile = open("bar.txt", "wb")
for l in lines:
ls = l.strip()
myfile.write(ls + "\n")
lsplit = ls.split("#")
myfile.write(lsplit[1] + "#" + lsplit[0] + "\n")
myfile.close()
There are cleaner ways to do this, but you could use something like:
f = open('my_file.txt', 'r')
lines = f.readlines()
f.close()
outfile = open('my_file2.txt', 'w')
# write each line, followed by flipped line
for line in lines:
outfile.write('%s\n' % line)
parts = line.split('#')
outfile.write('%s#%s\n' % [parts[1], parts[0]])
outfile.close()
You can use open and read function to read your file and than use this function,
>>> st = "x1#y1"
>>> def myfunc(string):
... mylist = re.split(r'(#)',string)
... mylist.reverse()
... print "".join(mylist), string
...
>>> myfunc(st)
y1#x1 x1#y1
and than use write to write the strings into your new file.
def swap(delimiter="#", input="input.txt", ouput="output.txt"):
with open(input, "r") as input_file, open(ouput, "w") as output_file:
for line in input_file:
line = line.strip()
output_line = delimiter.join(reversed(line.split(delimiter)))
output_file.write(line+"\n")
output_file.write(output_line+"\n")
swap()
Riffing on #DSM:
with open(infilename) as infile, open(outfilename, 'w') as outfile:
lines = [line.rstrip() for line in infile]
outfile.write("\n".join("%s\n%s%s%s" (line, y, sep, x)
for line in lines
for x, y in line.split(sep)) + "\n")
lines could also be a generator statement instead of a list comprehension:
lines = (line.rstrip() for line in infile)
Later: I did not realize until now that OP wanted the original line followed by the reversed line. Adjusted accordingly.