How do I split a line down further in Python txt files? - python

I am trying to split a line down into smaller elements
Each line contains the birds' name and the number of times it has been seen. I am trying to display them both if the name matches but I can't find a way to split one line down further.
Here's my code:
with open("birdFile.txt", "w") as file:
numRecs = int(input("How many records do you wish to write? "))
for n in range(1,numRecs+1):
birdName = input("Enter bird name: ")
birdsReported = input("Enter number of bird reported: ")
file.write(birdName + birdsReported + ",")
with open("birdFile.txt", "r") as file:
birdNameSearch = input("What bird are you searching for? ")
for line in file:
file = line.split(",")
birdName = line[0]
birdsSeen = line[1]
if birdNameSearch == birdName:
print(birdName + ": " + birdsSeen)

You wrote
file.write(birdName + birdsReported + ",")
Notice that the , comma came after the number -- you want it
before, to separate name from number.
Also, you'll want a \n newline at end of line.
This is most conveniently accomplished with an f-string:
file.write(f'{birdName},{birdsReported}\n')
Consider using the csv module: https://docs.python.org/3/library/csv.html

Related

Can't import data from files into one line

I'm currently making this program that was given to me by my school and it's to write your own name in ASCII text art but that was just copying and pasting. I am trying to make it so the user enters an input and there their name is output. My program currently works except it doesnt stay on one line.
My code:
name = input("What is your name: ")
splitname = list(name)
for i in range(len(splitname)):
f=open(splitname[i] + ".txt","r")
contents = f.read()
print(contents)
And this is what it outputs:
I would like to get it all onto one line if possible, how would I do so?
The solution is a bit more complicated because you have to print out line by line, but you already need all the contents of the 'letter' files.
The solution would be to read the first line of the first letter, then concatenate this string with the first line of the next letter and so on. Then do the same for the second line until you printed all lines.
I will not provide a complete solution, but I can help to fix your code. To start you have to only read one line of the letter file. You can do this with f.readline() instead of f.read() each consecutive call of this function will read the next line in this file, if the handle is still open.
To print the ASCII letters one next to the other, you have to split the letter into multiple lines and concatenate all the corresponding lines.
Assuming your ASCII text is made of 8 lines:
name = input("What is your name: ")
splitname = list(name)
# Put the right number of lines of the ASCII letter
letter_height = 8
# This will contain the new lines
# obtained concatenating the lines
# of the single letters
complete_lines = [""] * letter_height
for i in range(len(splitname)):
f = open(splitname[i] + ".txt","r")
contents = f.read()
# Split the letter in lines
lines = contents.splitlines()
# Concatenate the lines
for j in range(letter_height):
complete_lines[j] = complete_lines[j] + " " + lines[j]
# Print all the lines
for j in range(letter_height):
print(complete_lines[j])

Output process - save data in file

Briefly, I'm testing this code in python:
My idea is to save solut = one + two in a file after inputting the values by keyboard, but now I have a problem. NO message error and nothing is written in file.
python 2.7
I have changed and saved the code and failed and I don't have a backup. I canĀ“t remember how I need to handle an integer and convert in a pointer.
filex = open('test.txt', 'a+')
one = input("first number : \n -> ")
two = input("second number: \n -> ")
solut = one + two
for line in filex:
line = filex.writelines(solut)
filex.close()
Try this:
one = int(input("first number : \n -> "))
two = int(input("second number: \n -> "))
solut = one + two
with open('test.txt', 'a+') as filex:
filex.writelines([str(solut)])
You can use the int() function to convert the string that is input to an integer. Writelines() accepts a list of strings.
If you want to write the variable to a file, use the following code:
with open('test.txt', 'a+') as inputfile:
one = int(raw_input())
two = int(raw_input())
sum = one + two
inputfile.write(str(sum))

Why does it write to 2 lines in a text file when I only ask it to type 1?

Basically I need to write a line to a txt file containing details about a product, these details are from another text file which I split. The final detail which is the quantity variable is an inputted number.
document = open('Task2.txt', 'r')
strquantity = str(quantity)
for line in document:
the_line = line.split(",")
if the_line[0] == GTIN:
with open("receipt.txt", "a") as receipt:
receipt.write(the_line[0] + "," + the_line[1]+ "," +the_line[2] + "," + strquantity)
document.close()
The task 2 file contains:
12345670,spatula,0.99
57954363,car,1000.20
09499997,towel,1.20
The quantity number is 5 and the GTIN number is 12345670. The line it should write to the file is:
12345670,spatula,0.99,5
But instead it writes:
12345670,spatula,0.99,
5
(no line space (five on the next line under))
Why does it do this and how do I make it so it just writes to the 1 line? Thanks.
The reason is because when you read in each line, it will have a newline at the end. So when you call split, the final entry will also contain a newline, so when you write the_list[2] it will split the line at this point. To get around this, call strip() to remove the newline as follows:
with open('Task2.txt', 'r') as document, open("receipt.txt", "a") as receipt:
strquantity = str(quantity)
for line in document:
the_line = line.strip().split(",")
if the_line[0] == GTIN:
receipt.write(','.join(the_line[0], the_line[1], the_line[2], strquantity) + '\n')
you need to trim the newline character from each line just before exploding it.
the_line=line.strip()
the_line=the_line.split(",")

Python Search a .txt file and when a match is found print a number of lines after the matching word

Im looking to search a file and when the word im looking for has been found i want it to print the 8 lines below that word. Keep in mind im a complete noob and ive only been doing this for a few weeks. This is what i have but it doesn't work (obviously!):
name = input("What did you put as the calculation name?: ")
saved_calcs = open("saved_calcs.txt", "r")
lines = saved_calcs.read()
i = lines.index(name)
for line in lines[i-0:i+9]:
print (line)
saved_calcs.close()
lines.index will look for a line that is exactly name.
You need to go through the lines and search for your string.
i = -1
for x, line in enumerate(lines):
if line.find(name) != -1:
i = x
break
....
Not sure if this is what you are looking for, but if your input exactly matches the content in a line from the file, the code could be something like this:
name = input("What did you put as the calculation name?: ")
saved_calcs = open("saved_calcs.txt", "r")
lines = saved_calcs.read()
split_lines = lines.split("\n")
index = split_lines.index(str(name))+1
for line in split_lines[index:index+8]:
print line
saved_calcs.close()

Wordcounts line breaks in python

I'm trying to write a script to pull the word count of many files within a directory. I have it working fairly close to what I want, but there is one part that is throwing me off. The code so far is:
import glob
directory = "/Users/.../.../files/*"
output = "/Users/.../.../output.txt"
filepath = glob.glob(directory)
def wordCount(filepath):
for file in filepath:
name = file
fileO = open(file, 'r')
for line in fileO:
sentences = 0
sentences += line.count('.') + line.count('!') + line.count('?')
tempwords = line.split()
words = 0
words += len(tempwords)
outputO = open(output, "a")
outputO.write("Name: " + name + "\n" + "Words: " + str(words) + "\n")
wordCount(filepath)
This writes the word counts to a file named "output.txt" and gives me output that looks like this:
Name: /Users/..../..../files/Bush1989.02.9.txt
Words: 10
Name: /Users/..../..../files/Bush1989.02.9.txt
Words: 0
Name: /Users/..../..../files/Bush1989.02.9.txt
Words: 3
Name: /Users/..../..../files/Bush1989.02.9.txt
Words: 0
Name: /Users/..../..../files/Bush1989.02.9.txt
Words: 4821
And this repeats for each file in the directory. As you can see, it gives me multiple counts for each file. The files are formatted such as:
Address on Administration Goals Before a Joint Session of Congress
February 9, 1989
Mr. Speaker, Mr. President, and distinguished Members of the House and
Senate...
So, it seems that the script is giving me a count of each "part" of the file, such as the 10 words on the first line, 0 on the line break, 3 on the next, 0 on the next, and then the count for the body of the text.
What I'm looking for is a single count for each file. Any help/direction is appreciated.
The last two lines of your inner loop, which print out the filename and word count, should be part of the outer loop, not the inner loop - as it is, they're being run once per line.
You're also resetting the sentence and word counts for each line - these should be in the outer loop, before the start of the inner loop.
Here's what your code should look like after the changes:
import glob
directory = "/Users/.../.../files/*"
output = "/Users/.../.../output.txt"
filepath = glob.glob(directory)
def wordCount(filepath):
for file in filepath:
name = file
fileO = open(file, 'r')
sentences = 0
words = 0
for line in fileO:
sentences += line.count('.') + line.count('!') + line.count('?')
tempwords = line.split()
words += len(tempwords)
outputO = open(output, "a")
outputO.write("Name: " + name + "\n" + "Words: " + str(words) + "\n")
wordCount(filepath)
Isn't your identation wrong? I mean, the last lines are called once per line, but you really mean once per file, don't you?
(besides, try to avoid "file" as an identifier - it is a Python type)

Categories