Subtracting Numbers From A .txt File In Python - python

I want to be able to open the file i have, and append it so that if i want to subtract the number in the file by 2, it would print out the answer in the console by opening the file and reading it.
e.g. if the number in the file was 156, i would have to subtract it by 2, which is 154, this will then be displayed on the console!
this is all i have so far:
a = file.open("xp.txt", "r")
a.read()
a.close()
How would i update it so that if i wanted to subtract it by an integer, that integer would be displayed on console?
Thanks in advance!

Use readline instead of read so that you won't get an error when the file for example contains another empty line. Then, call strip on the result to eliminate possible whitespace. Finally, use int to convert the string to a number. Now you can do all the math you want with it:
with open("xp.txt", "r") as infile:
value = infile.readline()
stripped = value.strip()
number = int(stripped)
newNumber = number - 2
print(newNumber)
Or shorter:
with open("xp.txt", "r") as infile:
print(int(infile.readline().strip()) - 2)
To write the number to the same file, convert the number back to a string:
with open("xp.txt", "r") as infile:
result = int(infile.readline().strip()) - 2
print(result)
with open("xp.txt" , "w") as outfile:
outfile.write(str(result))

Assuming the file just contained that single value and nothing else, you could accomplish this using the following
with open('xp.txt', 'r') as f_in:
value = int(a.read())
value -= 2
print(f'New value is {value}')
with open('xp.txt', 'w') as f_out:
f_out.write(str(value))
Basically you open the file for reading, read the value into an integer, modify the value and display it, then re-open the file for writing to write the value back out.

Related

Python: replace string in each line

I'm trying to replace each "zzz" with a number. There is no output at execution and the file content remains the same. Here's what I have:
n = 0
file = open("filename", "a")
for line in file:
if "zzz" in line:
line.replace("zzz", n, 1)
n += 1
There are a few issues here. First, the replace method doesn't alter the string in place but rather creates a new string. Therefore, if you don't assign the new value to something, you're going to lose it.
Second, you're trying to read from the file but you're opening it in append mode. You need to open it with "r" instead of "a".
Third, you can't pass an integer (n) as the second argument to replace. You need to convert it to a string.
Finally, you're not writing the contents back to the file. That's why it's unchanged. I recommend reading all of the data in, altering it, and then re-opening the file in write mode.
n = 0
with open("filename", "r") as f:
lines = f.readlines()
for k, line in enumerate(lines):
if "zzz" in line:
lines[k] = line.replace("zzz", str(n), 1)
n += 1
with open("filename", "w") as f:
f.write("".join(lines))

How do I split each line into two strings and print without the comma?

I'm trying to have output to be without commas, and separate each line into two strings and print them.
My code so far yields:
173,70
134,63
122,61
140,68
201,75
222,78
183,71
144,69
But i'd like it to print it out without the comma and the values on each line separated as strings.
if __name__ == '__main__':
# Complete main section of code
file_name = "data.txt"
# Open the file for reading here
my_file = open('data.txt')
lines = my_file.read()
with open('data.txt') as f:
for line in f:
lines.split()
lines.replace(',', ' ')
print(lines)
In your sample code, line contains the full content of the file as a str.
my_file = open('data.txt')
lines = my_file.read()
You then later re-open the file to iterate the lines:
with open('data.txt') as f:
for line in f:
lines.split()
lines.replace(',', ' ')
Note, however, str.split and str.replace do not modify the existing value, as strs in python are immutable. Also note you are operating on lines there, rather than the for-loop variable line.
Instead, you'll need to assign the result of those functions into new values, or give them as arguments (E.g., to print). So you'll want to open the file, iterate over the lines and print the value with the "," replaced with a " ":
with open("data.txt") as f:
for line in f:
print(line.replace(",", " "))
Or, since you are operating on the whole file anyway:
with open("data.txt") as f:
print(f.read().replace(",", " "))
Or, as your file appears to be CSV content, you may wish to use the csv module from the standard library instead:
import csv
with open("data.txt", newline="") as csvfile:
for row in csv.reader(csvfile):
print(*row)
with open('data.txt', 'r') as f:
for line in f:
for value in line.split(','):
print(value)
while python can offer us several ways to open files this is the prefered one for working with files. becuase we are opening the file in lazy mode (this is the prefered one espicialy for large files), and after exiting the with scope (identation block) the file io will be closed automaticly by the system.
here we are openening the file in read mode. files folow the iterator polices, so we can iterrate over them like lists. each line is a true line in the file and is a string type.
After getting the line, in line variable, we split (see str.split()) the line into 2 tokens, one before the comma and the other after the comma. split return new constructed list of strings. if you need to omit some unwanted characters you can use the str.strip() method. usualy strip and split combined together.
elegant and efficient file reading - method 1
with open("data.txt", 'r') as io:
for line in io:
sl=io.split(',') # now sl is a list of strings.
print("{} {}".format(sl[0],sl[1])) #now we use the format, for printing the results on the screen.
non elegant, but efficient file reading - method 2
fp = open("data.txt", 'r')
line = None
while (line=fp.readline()) != '': #when line become empty string, EOF have been reached. the end of file!
sl=line.split(',')
print("{} {}".format(sl[0],sl[1]))

How to delete several lines in txt with conditional

everyone! I have just started learning python
I have a problem with some txt file
I want to delete all data with KMAG less than 5.5
but I have no idea any suggestions?
code below just what I could
file = open("experiment.txt", "r")
for line in file:
if 'KMAG' in line:
print(line)
file.close()
enter image description here
You need to do two things. First, it appears that this file has multiline records delimited by a line with a single decimal number. Use that to read the file a record at a time:
import re
from decimal import Decimal
def get_records(fileobj):
record = []
for line in fileobj:
if re.match(r"\s*\d+\s*$", line):
# got new record, emit old
if record:
yield record
record = [line]
else:
record.append(line)
if record:
yield record
return
Now you can peek into each record to see if its data you want to keep. I'm using the decimal module because because the python binary float does not exactly represent decimal floats.
min_val = Decimal("5.5")
with open("experiment.txt") as infile, open("foo.txt", "w") as outfile:
for record in get_records(infile):
# we got record number\nheader\ndata with kmag\n...
kmag = re.split(r"\s+", record[2].strip())[-1]
if Decimal(kmag) >= min_val:
outfile.writelines(record)

ValueError: not enough values to unpack (expected 2, got 1) is keeping me from finishing my code

Hello i am trying to make a dictionary from a file in python and i keep getting this error. I have no idea how to fix it. Help would be much appreciated.
Here is my code:
dict = {}
f = open('example.txt', 'r')
row = f.read()
lines = row.split("\n")
for line in lines:
name, number = line.split(")")
dict[name] = number
f.close()
return dict
And here is how the file looks like:
a)b
b)c
abc)d
d)dac
Thanks in advance
read will add an extra blank line when it hits the end of the file.
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string or bytes object. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ('').
change your program to check if libe exists.
dict = {}
f = open('example.txt', 'r')
row = f.read()
lines = row.split("\n")
for line in lines:
if line:
name, number = line.split(")")
dict[name] = number
f.close()
return dict
reference: https://docs.python.org/3.3/tutorial/inputoutput.html#methods-of-file-objects
IMP: please do not use builtin name dict for a variable
you are getting an empty line by the last row.split. You can remove it as follows by checking for if line:
lines = [line for line in row.split("\n") if line]
In addition you shouldn't reuse the builtin name dict for a variable. And you are using return outside a function, which is invalid.

Read a multielement list, look for an element and print it out in python

I am writing a python script in order to write a tex file. But I had to use some information from another file. Such file has names of menus in each line that I need to use. I use split to have a list for each line of my "menu".
For example, I had to write a section with the each second element of my lists but after running, I got anything, what could I do?
This is roughly what I am doing:
texfile = open(outputtex.tex', 'w')
infile = open(txtfile.txt, 'r')
for line in infile.readlines():
linesplit = line.split('^')
for i in range(1,len(infile.readlines())):
texfile.write('\section{}\n'.format(linesplit[1]))
texfile.write('\\begin{figure*}[h!]\n')
texfile.write('\centering\n')
texfile.write('\includegraphics[scale=0.95]{pg_000%i.pdf}\n' %i)
texfile.write('\end{figure*}\n')
texfile.write('\\newpage\n')
texfile.write('\end{document}')
texfile.close()
By the way, in the inclugraphics line, I had to increace the number after pg_ from "0001" to "25050". Any clues??
I really appreciate your help.
I don't quite follow your question. But I see several errors in your code. Most importantly:
for line in infile.readlines():
...
...
for i in range(1,len(infile.readlines())):
Once you read a file, it's gone. (You can get it back, but in this case there's no point.) That means that the second call to readlines is yielding nothing, so len(infile.readlines()) == 0. Assuming what you've written here really is what you want to do (i.e. write file_len * (file_len - 1) + 1 lines?) then perhaps you should save the file to a list. Also, you didn't put quotes around your filenames, and your indentation is strange. Try this:
with open('txtfile.txt', 'r') as infile: # (with automatically closes infile)
in_lines = infile.readlines()
in_len = len(in_lines)
texfile = open('outputtex.tex', 'w')
for line in in_lines:
linesplit = line.split('^')
for i in range(1, in_len):
texfile.write('\section{}\n'.format(linesplit[1]))
texfile.write('\\begin{figure*}[h!]\n')
texfile.write('\centering\n')
texfile.write('\includegraphics[scale=0.95]{pg_000%i.pdf}\n' %i)
texfile.write('\end{figure*}\n')
texfile.write('\\newpage\n')
texfile.write('\end{document}')
texfile.close()
Perhaps you don't actually want nested loops?
infile = open('txtfile.txt', 'r')
texfile = open('outputtex.tex', 'w')
for line_number, line in enumerate(infile):
linesplit = line.split('^')
texfile.write('\section{{{0}}}\n'.format(linesplit[1]))
texfile.write('\\begin{figure*}[h!]\n')
texfile.write('\centering\n')
texfile.write('\includegraphics[scale=0.95]{pg_000%i.pdf}\n' % line_number)
texfile.write('\end{figure*}\n')
texfile.write('\\newpage\n')
texfile.write('\end{document}')
texfile.close()
infile.close()

Categories

Resources