so I just want to do some simple math addition
get number from the first file ( let's say it's 1)
and number from the second file ( let's say it's 2)
so what I'm getting is 12, not 3
I would really appreciate the help.
myfile = open('file.txt', "r")
onecaracter = myfile.read(2)
with open('liczba1.txt', 'w') as f:
print(onecaracter, file=f)
myfile = open('file.txt', "r")
twocaracter = myfile.read(myfile.seek(4))
with open('liczba22.txt', 'w') as f:
print(twocaracter, file=f)
with open('liczba1.txt', "r") as file:
z = file.read(1)
with open('liczba22.txt', "r") as fil:
b = fil.read(1)
print(z + b)
The variables z and b are likely str types, and the + operator is defined on str types as concatenation. You can cast the two variables as integers and they should add as you expect, i.e.:
print(int(z) + int(b))
To illustrate this, you can always print out the type of a variable:
print(type(z))
myfile = open('file.txt', "r")
onecaracter = myfile.read(2)
with open('liczba1.txt', 'w') as f:
print(onecaracter, file=f)
myfile = open('file.txt', "r")
twocaracter = myfile.read(myfile.seek(4))
with open('liczba22.txt', 'w') as f:
print(twocaracter, file=f)
with open('liczba1.txt', "r") as file:
z = file.read(1)
with open('liczba22.txt', "r") as fil:
b = fil.read(1)
print(int(z) + int(b))
you should do a type cast:
total = int(z) + int(b)
print(total)
Related
I want that if a word already exit in Dico.txt it doesn't write it again.
e = input("Mots: ")
f = e.split(" ")
with open("Dico.txt", "a") as f2:
for line in f:
for word in line.split():
f2.write(word + '\n')
You can use a list for this:
e = input("Mots: ")
f = e.split(" ")
u = []
with open("Dico.txt", "a") as f2:
for line in f:
for word in line.split():
if not word in u:
f2.write(word + '\n')
u.append(word)
else:
continue
#!/usr/bin/env python
f = open('Dico.txt', 'r')
f2 = open('new.txt', 'w')
w = input('The word? ')
for line in f:
for word in line.split():
l = line.replace(w, "")
f2.write(l.strip(" "))
i want to make a program that count the letter A in the texts
f = open('text.txt', 'r')
content = f.read()
i = 1
for each a in content:
i = i + 1``
print(i)
The best way to do this particular task is by using the built-in count() function. Then the code becomes:
f = open('text.txt', 'r')
content = f.read()
print(content.count("A"))
I think this is what you want:
with open('text.txt', 'r') as f:
i = 0
for char in f:
if char == 'a':
i += 1
print(f'There are {i} a\'s in the txt file.')
string.count(substring)
content.count("a")
I have a file as below, whenever there is a key with empty value, I want to delete the key and the empty quotes
My file
<items="20" product="abc" condition="new">
<items="10" product="" condition="new">
<items="50" product="xyz" condition="">
<items="" product="mno" condition="fair">
desired output
<items="20" product="abc" condition="new">
<items="10" condition="new">
<items="50" product="xyz">
<product="mno" condition="fair">
I tried somehting like this, this deleted only the quotes. I want to delete the quotes and the value before "="
f= open('test.txt','r')
A1=f.read()
for i in A1:
if i=="''":
A1.remove(i)
print A1
break
You could use a regular expression:
import re
with open('test.txt','r') as A1:
for i in A1:
print(re.sub('[a-z-]+=\"\" *', '', i))
A possible solution could be:
with open('test.txt','r+') as f:
for line in f:
Line=line[1:len(line)-1]
L=Line.split()
for k in L:
if("" not in k):
f.write(k)
f.write(" ")
You could write a function to pass the lines through:
with open('in_file', 'r') as f:
lines = f.readlines()
def process_line(line):
line = line.split('<')[1].rsplit('>')[0]
valids = [val for val in line.split(' ') if '""' not in val]
line = '<{}>\n'.format(' '.join(valids))
return line
with open('out_file', 'w') as f:
for line in lines:
f.write(process_line(line))
You can use regex,
with open('tmp.txt', 'r') as f_in:
with open('tmp_clean.txt', 'w') as f_outfile:
f_out = csv.writer(f_outfile)
for line in f_in:
line = line.strip()
row = []
if bool(re.search('(.*="")', line)):
line = re.sub('[a-z]+=\"\"', '',line)
row.append(line)
else:
row.append(line)
f_out.writerow(row)
When reading and printing through my files, printing through my cousole gives me the correct result, but writing to the outfile does not
with infile as f :
lines = f.readlines()
new_line = " "
for line in lines:
new_line = ''.join(line).replace('*',letter.upper())
new_line = new_line.replace(':',letter.lower())
print(new_line)
This prints out all of the letters that I inputted
with infile as f :
lines = f.readlines()
new_line = " "
for line in lines:
new_line = ''.join(line).replace('*',letter.upper())
new_line = new_line.replace(':',letter.lower())
outfile.write(new_line)
It only gives me the last letter of the word inputted.
folder = r"C:\Users\sarah\Documents\a CPS 111\Bonus PA\stars\stars"
# os.listdir(folder) returns a list of files in folder
file_list = os.listdir(folder)
letter_art = {}
word = str(input("Please input a letter: "))
word = word.upper()
for fname in file_list:
letter_extension_list = fname.split(".")
for letter in word:
key = letter
value = letter_extension_list[1]
value = "%s."%(key) + value
letter_art[key] = value
fname = "\\".join([folder, value])
infile = open(fname, "r")
outfile = open("word_art.txt", "w")
with infile as f :
lines = f.readlines()
new_line = " "
for line in lines:
new_line = ''.join(line).replace('*',letter.upper())
new_line = new_line.replace(':',letter.lower())
print(new_line)
outfile.write(new_line)
infile.close()
outfile.close()
This is the code I am currently working with. I am taking in symbols from a txt file and changing them to the coornading letter depending on what the user inputed
Open the output file before the loop instead of within it:
outfile = open("word_art.txt", "w")
for letter in word:
with open("test.txt",'r') as f :
lines = f.readlines()
with open('out.txt','w') as outfile:
for line in lines:
new_line = line.replace('*',letter.upper())
new_line = new_line.replace(':',letter.lower())
outfile.write(new_line)
This worked for me.
EDIT:
TigerhawkT3 is correct. I checked out your full code and you were opening the file again and again inside the loop, each time discarding the prior changes.
For instance if a file has
xxx|12
yyy|13
zzz|14
I need the output to be
1 xxx|12
2 yyy|13
3 zzz|14
How can I achieve that?
import fileinput
f=fileinput.FileInput("file",inplace=1)
for line in f:
print f.lineno(), line
there are many other ways to do it. If you are on a linux/unix system
awk '{print NR,$0}' file
cat -n file
sed '=' file
nl file
Also Ruby(1.9+)
ruby -ne 'print "#{$.} #{$_}"' file
inputfile = open('filein.txt', 'r')
outputfile = open('fileout.txt', 'w')
count = 1
for line in inputfile:
outputfile.write(str(count) + " " + line)
count += 1
outputfile.close()
inputfile.close()
et voile.
inputfile = open('filein.txt', 'r')
outputfile = open('fileout.txt', 'w')
for index, line in enumerate(inputfile, 1):
outputfile.write("%d %s" %(index, line))
outputfile.close()
inputfile.close()
I noticed that your input had some empty lines, anyway here you go:
text=open('input.txt','r')
lines=text.readlines()
text.close()
output=open('output.txt','w')
for lineNumber in range(len(lines)):
if lines[lineNumber] not in ["","\n","\t"]:
output.write(str(lineNumber)+" "+lines[lineNumber])
else:
output.write(lines[lineNumber])
Use enumerate().
f = open('input_file')
data = f.read().split()
f.close()
data = ["%d %s" % (idx + 1, x) for idx, x in enumerate(data)]
data = " ".join(data)
f = open('output_file', 'w')
f.write(data)
f.close()