merge several input in one python - python

My input will be several separate line in the same form. I don't know how can I merge these inputs to one object.
For example:
Robin 590.00 343.05 3333.00
Max 45.00 234.44 3443.55
and I would like to have these data in one expression
(data = '''Robin 590.00 343.05 3333.00 Max 45.00 234.44 3443.55 ''')
because I want to execute this code (I have to sum up last value of every input line):
result = sum(float(x.split()[-1]) for x in data.splitlines())

Most of the things that you need to read a file are in the python manual. More specifically, you can use the with open command to get a list as shown below. The list comprehension is to remove any trailing new line characters (strip) and keep your data in a variable, since f will be closed as soon as you exit the with clause.
with open('test.txt') as f:
fout = [fone.strip('\n')for fone in f]
print(fout)

Related

TypeError: write() argument must be str, not list - How do I convert a list into a text file to be stored?

houses = []
#print(houses)
#Creates an empty list for the houses
f = open("houses.txt", "r+")
#Creates a variable called "f" which opens the houses.txt file and imports it r+ = Read and + means you can append on the end
lines = f.readlines()
#The readlines() method returns a list containing each line in the file as a list item. Use the hint parameter to limit the number of lines returned.
#The for loop grabs each line of text from the file, and splits the houses and scores and makes them separate. It runs for as many lines are in the text file
for line in lines:
#The append adds the stripped and split code separately in a list
#.strip .split separates the houses and scores into separate strings
houses.append(line.strip().split())
for i in range(len(houses)):
#Loops for how many houses are in the list
houses[i][1] = int(houses[i][1])
#Turns the second part of the list into an integer
print(houses)
This part of the code imports houses (teams) from the text file which is laid out like this:
StTeresa 0
StKolbe 0
StMary 0
StAnn 0
I created a function to save the points. I would basically like it to take the houses and scores from the list in the program. To do so, it will delete all the contents in the text file, and then I would like it to rewrite it in the same format as the original text file to keep the updated house scores.
def save():
f.truncate(0)
f.write(str(houses))
I tried this but the output is:
This
Can anyone help me to rewrite the text file to include the updated scores and be in the same format as the text file orignally was?
This should accomplish what you want:
def save():
with open("houses.txt", "w") as file:
for index, line_content in enumerate(houses):
houses[index][1] = str(houses[index][1])
file.write("\n".join(map(lambda sub_list: " ".join(sub_list), houses)))
However, as you can see, this is quite hacky.
So I would have two main recommendations for your code:
Use open() within a with statement. Currently your code does not reliably close the file it opens, which can cause your code to do unexpected things (for example when an exception is thrown in the middle of your processing). Therefore, it is recommended practice to use with (further information on this can be found here)
Instead of using lists within a list, you could use tuples:
for line in lines:
# The append adds the stripped and split code separately in a list
# .strip .split separates the houses and scores into separate strings
house_name, house_score = tuple(line.strip().split())
houses.append((house_name, int(house_score)))
This gives you something like this: [("StTeresa", 0), ("StKolbe", 0), ("StMary", 0), ("StAnn", 0)]. Tuples in lists have the advantage that you can unpack them in loops, which makes it easier to handle them compared to a list within a list:
for index, (house_name, house_score) in enumerate(houses):
# do something with the score
houses[index] = (house_name, updated_score)
Another option is to follow what Barmar suggested and use the csv module, which is part of the standard library.
As a bonus: enumerate() provides you the indices of an iterable, so you can easily loop over them. So instead of
for i in range(len(houses)):
#Loops for how many houses are in the list
you can write
for i, house in enumerate(houses):
# Loop over all the houses
which makes the code a little easier to read and write.
So with all my suggestions combined you could have a save() function like this:
def save():
with open("houses.txt", "w") as file:
for house_name, house_score in houses:
file.write(f"{house_name} {house_score}\n")
Hope this helps :)

Adding a comma to the end of every row in python

I have a list of sample codes which I input into a website to get information about each of them (they are codes for stars, but it doesn't matter what the codes are, they are just a long string of numbers). All these numbers are in one column, one number per row. The website I need to input this file into accepts the numbers to still be in a column, but with a comma next to the numbers. This is an example:
Instead of:
164891738509173
184818483848283
18483943491u385
It's supposed to look like this:
164891738509173,
184818483848283,
18483943491u385,
I wanted to program a quick python code to do that automatically for each number in the entire column. How do I do that? I can manage theoretically to do that manually if the number of stars I'm dealing with is little, but unfortunately in the website, I need to input something like 60000 stars (so 60000 of these numbers) so doing it manually is suicide.
Very simple:
open('output.txt', 'w').writelines( # open 'output.txt' for writing and write multiple lines
line.rstrip('\n') + ',\n' # append comma to each line
for line in open('input.txt') # read lines with numbers from 'input.txt'
)
You could do it more idiomatically and use a with block, but that's probably overkill for such a small task:
with open('input.txt') as In, open('output.txt', 'w') as Out:
for line in In:
Out.write(line.rstrip('\n') + ',\n')
Is this what you want?
If you want to add comma at end the every entry during printing, you can do this:
>>> codes = ['164891738509173', '184818483848283', '18483943491u385']
>>> for code in codes:
... print(code, end=',\n')
...
164891738509173,
184818483848283,
18483943491u385,
To add a comma to every item within the list,
>>> end_comma = [f"{code}," for code in codes]
>>> end_comma
['164891738509173,', '184818483848283,', '18483943491u385,']

Use of readline()?

I have a question about this program:
%%file data.csv
x1,x2,y
0.4946,5.7661,0
4.7206,5.7661,1
1.2888,5.3433,0
4.2898,5.3433,1
1.4293,4.5592,0
4.2286,4.5592,1
1.1921,5.8563,0
3.1454,5.8563,1
f = open('data.csv')
data = []
f.readline()
for line in f:
(x1,x2,y) = line.split(',')
x1 = float(x1)
x2 = float(x2)
y = int(y)
data.append((x1,x2,y))
What is the purpose of readline here? I have seen different examples but here seems that it delete the first line.
Python is reading the data serially, so if a line gets read once, python jumps to the next one. The r.readline() reads the first line, so in the loop it doesn't get read.
That's precisely the point: to delete the first line. If you notice, the file has the names of the columns as its first line (x1,x2,y), and the program wants to ignore that line.
Using readline() method before reading lines of file in loop
is equals to:
for line in f.readlines()[1:]:
...
for example that may be used to skip table header.
In your file, when you will convert x1 variable to float type it raise ValueError because in first iteration x1 contain not digit sting type value "x1". And to avoid that error you use readline() to swich iterator to second line wich contain pure digits.

Read from file and write to another python

I have a file with contents as given below,
to-56 Olive 850.00 10 10
to-78 Sauce 950.00 25 20
to-65 Green 100.00 6 10
If the 4th column of data is less than or equal to the 5th column, the data should be written to a second file.
I tried the following code, but only 'to-56 Olive' is saved in the second file. I can't figure out what I'm doing wrong here.
file1=open("inventory.txt","r")
file2=open("purchasing.txt","w")
data=file1.readline()
for line in file1:
items=data.strip()
item=items.split()
qty=int(item[3])
reorder=int(item[4])
if qty<=reorder:
file2.write(item[0]+"\t"+item[1]+"\n")
file1.close()
file2.close()
You're reading only one line of input. So, you can have at most one line of output.
I see that your code is a bit "old school". Here's a more "modern" and Pythonic version.
# Modern way to open files. The closing in handled cleanly
with open('inventory.txt', mode='r') as in_file, \
open('purchasing.txt', mode='w') as out_file:
# A file is iterable
# We can read each line with a simple for loop
for line in in_file:
# Tuple unpacking is more Pythonic and readable
# than using indices
ref, name, price, quantity, reorder = line.split()
# Turn strings into integers
quantity, reorder = int(quantity), int(reorder)
if quantity <= reorder:
# Use f-strings (Python 3) instead of concatenation
out_file.write(f'{ref}\t{name}\n')
I've changed your code a tiny bit, all you need to do is iterate over lines in your file - like this:
file1=open("inventory.txt","r")
file2=open("purchasing.txt","w")
# Iterate over each line in the file
for line in file1.readlines():
# Separate each item in the line
items=line.split()
# Retrieve important bits
qty=int(items[3])
reorder=int(items[4])
# Write to the file if conditions are met
if qty<=reorder:
file2.write(items[0]+"\t"+items[1]+"\n")
# Release used resources
file1.close()
file2.close()
Here is the output in purchasing.txt:
to-56 Olive
to-65 Green

Converting .txt file to list AND be able to index and print list line by line

I want to be able to read the file line by line and then when prompted (say user inputs 'background'), it returns lines 0:24 because those are the lines in the .txt that relate to his/her background.
def anaximander_background():
f = open('Anaximander.txt', 'r')
fList = []
fList = f.readlines()
fList = [item.strip('\n') for item in fList]
print(fList[:20])
This code prints me the list like:
['ANAXIMANDER', '', 'Anaximander was born in Miletus in 611 or 610 BCE.', ...]
I've tried a lot of different ways (for, if, and while loops) and tried the csv import.
The closest I've gotten was being able to have a print out akin to:
[ANAXIMANDER]
[]
[info]
and so on, depending on how many objects I retrieve from fList.
I really want it to print like the example I just showed but without the list brackets ([ ]).
Definitely can clarify if necessary.
Either loop over the list, or use str.join():
for line in fList[:20]:
print(line)
or
print('\n'.join(fList[:20])
The first print each element contained in the fList slice separately, the second joins the lines into a new string with \n newline characters between them before printing.
To print the first 20 lines from a file:
import sys
from itertools import islice
with open('Anaximander.txt') as file:
sys.stdout.writelines(islice(file, 20))

Categories

Resources