hello,PLease help me with txt.in Python - python

have to write in python 2 txt.files one is input of numbers: writen in 2 lines 4-1 and 12-3 I have to make the subtraction and write the result to other txt.file
please help me I am very green to python, just started to learn it.
Thanks you all in advance
this is what I managed to write till now:
import calculator
with open ('./expresii.txt', 'r') as f:
line = f.readlines()
for l in line:
if l[1] == '-':
print(calculator.subtraction(int(l[0]), int(l[2])))
else:
print(calculator.addition(int(l[0]), int(l[2])))
with open ('./expresii.txt', 'r') as f2:
print(f2.read())
in first I get the subtraction of numbers
and from the second I get the numbers that must be subtrated
now how do I write toa new file 4-1=3 and 12-3=9 this must be the result

Here is a Python 2.7 Solution:
import re
# opens the input file in readmode
with open ('expresii.txt', 'r') as f:
# creates an iterable of the lines in the file
lines = f.readlines()
# create an empty array which will store the data to write to the output file
to_file = []
# loops through every line in the file
for l in lines:
# creates a list of ints of all the numbers in that line
nums = list(map(int, re.findall(r'\d+', l)))
# calculate the result by subtracting the two numbers
result = nums[0] - nums[1]
# append answer (e.g 4-1=3) to a list, that will later be written to a file
line = str(nums[0])+'-'+str(nums[1])+'='+str(result)+'\n'
to_file.append(line)
#open the output file in write mode
with open('output_file.txt', 'w') as f:
# write the to_file list to output_file.txt
f.writelines(to_file)
This solution finds all of the numbers, in each line of the file, and calculates the result when you subtract them. After it has done this for every line in the input file, it then writes this data to an output file.
I wish you well as you continue to learn Python :)

Related

Best way to count the number of deleted lines from a file using python

I'm wondering what is the easiest way to count the number of deleted lines from a file using python. Is it taking the index of lines before and after and subtracting? Or is there a way to count the number lines deleted in a loop?
In my sample file below, I have a before user-input file and an after file that is written to exclude any lines from the user input that has negative numbers or blank spaces. I realize I will either need to count the before and after files, or find a way to count the items in the note_consider[] list.
import os, sys
inFile = sys.argv[1]
baseN = os.path.basename(inFile)
outFile = 'c:/example.txt'
#if path exists, read and write file
if os.path.exists(inFile):
inf = open(inFile,'r')
outf = open(outFile,'w')
#reading and writing header
header = inf.readline()
outf.write(header)
not_consider = []
lines = inf.read().splitlines()
for i in range(0,len(lines)):
data = lines[i].split("\t")
for j in range(0,len(data)):
if (data[j] == '' or float(data[j]) < 0):
#if line is having blank or negtive value
# append i value to the not_consider list
not_consider.append(i)
for i in range(0,len(lines)):
#if i is in not_consider list, don't write to out file
if i not in not_consider:
outf.write(lines[i])
print(lines[i])
outf.write("\n")
inf.close()
outf.close()
This code reads a file in input and write the lines that are not empty or numbers in an output file. Was that what you expected ?
If you don't use the information about the not_considered lines, then you can remove the associated code, and replace the for line_idx, line in enumerate(ifile.readlines()): with for line in ifile.readlines():.
The with open(<filename>, <mode>) as file: statement takes care of opening the file and closing it for you when living the scope of the statement.
def is_number(line: str):
try:
float(line)
return True
except ValueError:
return False
with open("./file.txt", "r") as ifile, open("output.txt", "w") as ofile:
not_considered = []
for line_idx, line in enumerate(ifile.readlines()):
if line == "\n" or is_number(line):
not_considered.append(line_idx)
continue
ofile.write(line)
print(f"not considered : {not_considered}")
print(f"n not considered: {len(not_considered)}")
input file:
this is
1234
a
file
with a lot
42
of empty lines
output file:
this is
a
file
with a lot
of empty lines
console output:
not considered : [1, 2, 3, 5, 7, 9, 10]
n not considered: 7

Reading strings and decreasing them

I just have a simple question when dealing with text files:
I have a text file and want to make a python program to read it and if it finds any number it replaces it by the number preceding it like if it finds 4 it replaces it with 3 so how can I do that?
The problem for me in this program is that python reads the numbers as strings, not integers, so it can't decrease or increase them.
out = open("out.txt", "w")
with open("Spider-Man.Homecoming.2017.1080p.BluRay.x264-[YTS.AG].txt", "r") as file:
lines = file.readlines()
for line in lines:
if line.isdigit():
out.write(str(int(line - 1)))
else:
out.write(line)
This code doesn't detect the numbers as numbers and I don't know why.
Putting #Samwise's comment together with your code:
with open("Spider-Man.Homecoming.2017.1080p.BluRay.x264-[YTS.AG].txt", "r") as file:
lines = file.readlines()
new_lines = []
for line in lines:
decreased = ''.join(str(int(c)-1) if c.isdigit() else c for c in line)
new_lines.append(decreased)
with open('out.txt', 'w') as out:
out.writelines(new_lines)
You also should close the file after writing to it, so switched to with open at the end as a better way to write to file.

How to generate a file with a list of 10 random numbers, sort them and write to a new file

PYTHON. Generate a file numbers.txt filled with a list of 10 random numbers. Read the numbers,
sort them and write to a new file sorted_numbers.txt.
I have this, it only reads. I don't know how to sort it.
f= open("numbers.txt","w+")
line=(random.sample(range(100),10))
line2=str(line)
f.write(line2)
#print(line)
f.close()
f=open("numbers.txt", "r")
if f.mode == 'r':
contents =f.read()
print(contents)
f.close() ```
with open ('numbers.txt', 'r') as f:
new_list = sorted([int(i.replace('\n', '')) for i in f.readlines()])
with open ('sorted_numbers.txt', 'w') as f:
for i in new_list:
f.write(str(i) + '\n')
This should work.
it takes the original txt file (numbers.txt) and go over the numbers and sort them to a new SORTED list, after that it writes the sorted numbers to a new txt file (sorted_numbers.txt).
Edit:
import random
# create a list with random 10 numbers in range of (0 - 100)
random_list = [random.randint(0, 100) for i in range(10)]
# create a file with those numbers (unsorted!)
with open('numbers.txt', 'w') as file:
for n in random_list:
file.write(str(n) + '\n')
# create a new file and add the sorted numbers this time
with open ('numbers.txt', 'r') as read_file:
# sort the list
new_list = sorted([int(i.replace('\n', '')) for i in read_file.readlines()])
with open ('sorted_numbers.txt', 'w') as write_file:
for j in new_list:
write_file.write(str(j) + '\n')
This code creates all the files.
Its generate 10 random nums and create a file with the numbers, then read this file and sort the numbers and write it to the a new sorted txt file.
First of all, you should convert the numbers from a string form to an int:
for i in range(len(contents)):
contents[i]=int(contents[i])
Once you've done that you can just use sort():
contents.sort()
And you are done.
Hope it works.

Dividing a .txt file in multiple parts in Python

I'm a begginer in Python, and I have a question about file reading :
I need to process info in a file to write it in another one. I know how to do that, but it's reaaally ressource-consuming for my computer, as the file is really big, but I know how it's formatted !
The file follows that format :
4 13
9 3 4 7
3 3 3 3
3 5 2 1
I won't explain what it is for, as it would take ages and would not be very useful, but the file is essentialy made of four lines like these, again and again. For now, I use this to read the file and convert it in a very long chain :
inputfile = open("input.txt", "r")
output = open("output.txt", "w")
Chain = inputfile.read()
Chain = Chain.split("\n")
Chained = ' '.join(Chain)
Chain = Chained.split(" ")
Chain = list(map(int, Chain))
Afterwards, I just treat it with "task IDs", but I feel like it's really not efficient.
So do you know how I could divide the chain into multiple ones knowing how they are formatted?
Thanks for reading !
How about:
res = []
with open('file', 'r') as f:
for line in f:
for num in line.split(' '):
res.append(int(num))
Instead of reading the whole file into memory, you go line by line.
Does this help?
If you need to go 4 lines at a time, just add an internal loop.
Regarding output, I'm assuming you want to do some computation on the input, so I wouldn't necessarily do this in the same loop. Either process the input once reading is done, or instead of using a list, use a queue and have another thread read from the queue while this thread is writing to it.
Perhaps the utility of a list comprehension will help a bit as well (I doubt this will make an impact):
res = []
with open('file', 'r') as f:
for line in f:
res.append( int(num) for num in line.split() )
hmm there's some method to write to a file without reading it i believe
Add text to end of line without loading file
https://docs.python.org/2.7/library/functions.html#print
from __future__ import print_function
# if you are using python2.7
i = open("input","r")
f = open("output.txt","w")
a = "awesome"
for line in i:
#iterate lines in file input
line.strip()
#this will remove the \n in the end of the string
print(line,end=" ",file=f)
#this will write to file output with space at the end of it
this might help, i'm a newbie too, but with better google fu XD
Maybe do it line by line. This way it consumes less memory.
inputfile = open("input.txt", "r")
output = open("output.txt", "a")
while True:
line = inputfile.readline()
numbers = words.split(" ")
integers = list(map(int, numbers))
if not line:
break
There is probably a newline character \n in the words. You should also replace that with an empty string.
If you don't wanna to consume memory (you can run of it if file is very large), you need to read lien by line.
with open('input.txt', 'w') as inputfile, open('"output.txt', 'w') as output:
for line in inputfile:
chain = line.split(" ")
#do some calculations or what ever you need
#and write those numbers to new file
numbers = list(map(int, chain))
for number in numbers
output.write("%d " % number)

Same value in list keeps getting repeated when writing to text file

I'm a total noob to Python and need some help with my code.
The code is meant to take Input.txt [http://pastebin.com/bMdjrqFE], split it into seperate Pokemon (in a list), and then split that into seperate values which I use to reformat the data and write it to Output.txt.
However, when I run the program, only the last Pokemon gets outputted, 386 times. [http://pastebin.com/wkHzvvgE]
Here's my code:
f = open("Input.txt", "r")#opens the file (input.txt)
nf = open("Output.txt", "w")#opens the file (output.txt)
pokeData = []
for line in f:
#print "%r" % line
pokeData.append(line)
num = 0
tab = """ """
newl = """NEWL
"""
slash = "/"
while num != 386:
current = pokeData
current.append(line)
print current[num]
for tab in current:
words = tab.split()
print words
for newl in words:
nf.write('%s:{num:%s,species:"%s",types:["%s","%s"],baseStats:{hp:%s,atk:%s,def:%s,spa:%s,spd:%s,spe:%s},abilities:{0:"%s"},{1:"%s"},heightm:%s,weightkg:%s,color:"Who cares",eggGroups:["%s"],["%s"]},\n' % (str(words[2]).lower(),str(words[1]),str(words[2]),str(words[3]),str(words[4]),str(words[5]),str(words[6]),str(words[7]),str(words[8]),str(words[9]),str(words[10]),str(words[12]).replace("_"," "),str(words[12]),str(words[14]),str(words[15]),str(words[16]),str(words[16])))
num = num + 1
nf.close()
f.close()
There are quite a few problems with your program starting with the file reading.
To read the lines of a file to an array you can use file.readlines().
So instead of
f = open("Input.txt", "r")#opens the file (input.txt)
pokeData = []
for line in f:
#print "%r" % line
pokeData.append(line)
You can just do this
pokeData = open("Input.txt", "r").readlines() # This will return each line within an array.
Next you are misunderstanding the uses of for and while.
A for loop in python is designed to iterate through an array or list as shown below. I don't know what you were trying to do by for newl in words, a for loop will create a new variable and then iterate through an array setting the value of this new variable. Refer below.
array = ["one", "two", "three"]
for i in array: # i is created
print (i)
The output will be:
one
two
three
So to fix alot of this code you can replace the whole while loop with something like this.
(The code below is assuming your input file has been formatted such that all the words are split by tabs)
for line in pokeData:
words = line.split (tab) # Split the line by tabs
nf.write ('your very long and complicated string')
Other helpers
The formatted string that you write to the output file looks very similar to the JSON format. There is a builtin python module called json that can convert a native python dict type to a json string. This will probably make things alot easier for you but either way works.
Hope this helps

Categories