One print statement two variables get printed on two different lines - python

with open("C:\\Users\\Nav\\Desktop\\script\\names.txt", 'r+') as f:
for x in range (0, 100):
f_contents = f.readline()
name = f_contents
name2 = name
print(name.lower().replace(" ", "") + "#gmail.com" + "\n")
x = input()
With this code, I am trying to read a file with a full name on each line and format it, that works fine but when I add the "#gmail.com" and get it printed out it gets printed to two different lines in the console.
For example, my output is
austenrush
#gmail.com
yuvaanduncan
#gmail.com
jawadpatton
#gmail.com
hanifarusso
#gmail.com
kerysbeck
#gmail.com
safiyamcguire
#gmail.com
oluwatobilobamiddleton
#gmail.com
while I would like to get:
austenrush#gmail.com
yuvaanduncan#gmail.com
jawadpatton#gmail.com
hanifarusso#gmail.com
kerysbeck#gmail.com
safiyamcguire#gmail.com
oluwatobilobamiddleton#gmail.com

readline doesn't strip the newline read from the file; you have to do that yourself.
f_contents = f.readline().rstrip("\n")
Files are iterable, though, so you don't need to call readline explicitly.
from itertools import islice
with open("C:\\Users\\Nav\\Desktop\\script\\names.txt", 'r+') as f:
for f_contents in islice(f, 100):
name = f_contents.rstrip("\n").lower().replace(" ", "")
print(name + "#gmail.com" + "\n")
x = input()

Related

Writing to a text file, last entry is missing

This code calls no errors, but my text file is not getting betty and her grade. It's only getting the first three out of the four combinations. What am I doing wrong? Thanks!
students = ['fred','wilma','barney','betty']
grades = [100,75,80,90]
for i in range(4):
file = open("grades3.txt", "a")
entry = students[i] + "-" + str(grades[i]) + '\n'
file.write(entry)
file.close
You should use use with open() as ... to automatically open, close and assign the file handle to a variable:
students = ['fred','wilma','barney','betty']
grades = [100,75,80,90]
with open("grades3.txt", "a") as file:
for i in range(4):
entry = students[i] + "-" + str(grades[i]) + '\n'
file.write(entry)
It seems that you are opening the file each iteration of the loop, as well as not calling the file.close function. You should have something like this:
students = ['fred','wilma','barney','betty']
grades = [100,75,80,90]
file = open("grades3.txt", "a")
for i in range(4):
entry = students[i] + "-" + str(grades[i]) + '\n'
file.write(entry)
file.close()
It would be better if you use an approach like this instead of using range():
students = ['fred','wilma','barney','betty']
grades = [100,75,80,90]
with open("grades3.txt","a") as f:
for student, grade in zip(students,grades):
f.write(f"{student}-{grade}\n")

Adding data to a txt file (and saving it there)

I am a complete beginner with programming. I try to add some information to a txt file, but it doesn't work... It does print the parameters, but won't add it in the txt file. All the help will be appreciated.
def addpersons(student_number, name, phone_number):
new_person = student_number + name + phone_number
data = data + new_person
with open("data.txt", 'w') as f:
f.write (data)
print(200300, "Jim", "031213245123")
Is that all the code you have? Because you are adding data + person where data is not defined, that should throw an error. Which you probably don't see because if that is all your Code you are not calling the function add all.
To have it work make sure you acctually call the function addpersonand make sure that data is defined before you do data = data + person
Also there shouldn't be a space between f.write and (data) but I doubt that matters.
Here is a version that should work:
def addpersons(student_number, name, phone_number):
new_person = str(student_number) + name + phone_number
with open("data.txt", 'w') as f:
f.write(new_person)
addpersons(200300, "Jim", "031213245123")
print(200300, "Jim", "031213245123")
I took a look at your code and lets just say its completely wrong. Also in future please use the md feature with backticks to simply paste your code, it makes life much easier for people who try and answer, anyways i digress. Your first mistake is in this line
new_person = student_number + name + phone_number
Student_number is an integer, you cannot concat ints and strs in python, you can use the str() builtin to convert it to a string.
Your next error is:
data = data + new_person
data is not defined before this, i assume you are doing this so you can put multiple people in, however you can achieve this by appending to the file instead of writing. This is achievable by doing:
with open("data.txt", "a") as f:
Then you can just do:
with open("data.txt", "w") as f:
f.write(new_student)
Try this:
def addpersons(student_number, name, phone_number):
data = ""
new_person = str(student_number) + name + str(phone_number)
data = data + new_person
with open("data.txt", 'a') as f:
f.write(data + '\n')
addpersons(200300, "Jim", "03121324")
addpersons(12345, "Jorj", "098765434")
Output:
or Try this:
def addpersons(student_number, name, phone_number):
data = ""
new_person = str(student_number) + "\t" + name + "\t" + str(phone_number)
data = data + new_person
with open("data.txt", 'a') as f:
f.write(data + '\n')
addpersons(200300, "Jim", "03121324")
addpersons(12345, "Jorj", "098765434")
Output:

How do I get the details entered by the user to go onto a new line in the text file in python?

'''volunteerList.append([ [name], [coinType], [weight], [correct], "\n"])'''
the piece of code above is the code I have tried but the details entered end up on the same line and delete parts of the last set of details entered.
I am not sure where the file is in this example but you would want to do this not to overwrite a file:
name = "A"
coinType = "B"
weight = 99
correct = False
your_list = [ name, coinType, weight, correct]
text = "\n" + " ".join([str(x) for x in your_list])
with open("output.txt", "a") as f:
f.write(text)

formatted output to an external txt file

fp = open ('data.txt','r')
saveto = open('backup.txt','w')
someline = fp.readline()
savemodfile = ''
while someline :
temp_array = someline.split()
print('temp_array[1] {0:20} temp_array[0] {0:20}'.format(temp_array[1], temp_array[0]), '\trating:', temp_array[len(temp_array)-1]))
someline = fp.readline()
savemodfile = temp_array[1] + ' ' + temp_array[0] +',\t\trating:'+ temp_array[10]
saveto.write(savemodfile + '\n')
fp.close()
saveto.close()
The input file :data.txt has records of this pattern: firstname Lastname age address
I would like the backup.txt to has this format: Lastname firstname address age
How do i store the data in the backup.txt in a nice formatted way? I think i should use format() method somehow...
I use the print object in the code to show you what i understood about format() so far. Of course, i do not get the desired results.
To answer your question:
you can indeed use the .format() method on a string template, see the documentation https://docs.python.org/3.5/library/stdtypes.html#str.format
For example:
'the first parameter is {}, the second parameter is {}, the third one is {}'.format("this one", "that one", "there")
Will output: 'the first parameter is this one, the second parameter is that one, the third one is there'
You do not seem to use format() properly in your case: 'temp_array[1] {0:20} temp_array[0] {0:20}'.format(temp_array[1], temp_array[0]) will output something like 'temp_array[1] Lastname temp_array[0] Lastname '. That is because {0:20} will output the 1st parameter to format(), right padded with spaces to 20 characters.
Additionally, there is many things to be improved in your code. I guess you are learning Python so that's normal. Here is a functionally equivalent code that produces the output you want, and makes good use of Python features and syntax:
with open('data.txt', 'rt') as finput, \
open('backup.txt','wt') as foutput:
for line in finput:
firstname, lastname, age, address = line.strip().split()
foutput.write("{} {} {} {}\n".format(lastname, firstname, address, age)
This code will give you a formatted output on the screen and in the output file
fp = open ('data.txt','r')
saveto = open('backup.txt','w')
someline = fp.readline()
savemodfile = ''
while someline :
temp_array = someline.split()
str = '{:20}{:20}{:20}{:20}'.format(temp_array[1], temp_array[0], temp_array[2], temp_array[3])
print(str)
savemodfile = str
saveto.write(savemodfile + '\n')
someline = fp.readline()
fp.close()
saveto.close()
But this is not a very nice code in working with files, try using the following pattern:
with open('a', 'w') as a, open('b', 'w') as b:
do_something()
refer to : How can I open multiple files using "with open" in Python?
fp = open ('data.txt','r')
saveto = open('backup.txt','w')
someline = fp.readline()
savemodfile = ''
while someline :
temp_array = someline.split()
someline = fp.readline()
savemodfile = '{:^20} {:^20} {:^20} {:^20}'.format(temp_array[1],temp_array[0],temp_array[3],temp_array[2])
saveto.write(savemodfile + '\n')
fp.close()
saveto.close()

Copy 'N' lines from one file to another in python?

Essentially what I am attempting to do is read 'n' number of lines from a file and then write them to a separate file. This program essentially should take a file that has 100 lines and separate that file into 50 separate files.
def main():
from itertools import islice
userfile = raw_input("Please enter the file you wish to open\n(must be in this directory): ")
file1 = open(userfile, "r+")
#print "Name: ", file1.name
#print "Closed or not", file1.closed
#print "Opening mode: ", file1.mode
#print "Softspace flag: ", file1.softspace
jcardtop = file1.read(221);
#print jcardtop
n = 2
count = 0
while True:
next_n_lines = list(islice(file1,n))
print next_n_lines
count = count + 1
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(jcardtop))
fileout.write(str(next_n_lines))
fileout.close()
break
if not next_n_lines:
break
I do have the file printing as well to show what is in the variable next_n_lines.
*['\n', "randomtext' more junk here\n"]
I would like it instead to look like
randomtext' more junk here
Is this a limitatoin of the islice function? Or am I missing a portion of the syntax?
Thanks for your time!
Where you call str() or print, you want to ''.join(next_n_lines) instead:
print ''.join(next_n_lines)
and
fileout.write(''.join(next_n_lines))
You can store the flattened string in a variable if you don't want to call join twice.
Did you mean something like this?
f = open(userfile,"r")
start = 4
n_lines = 100
for line in f.readlines()[start:(start + n_lines)]:
print line
#do stuff with line
or maybe this rough, yet effective code:
f = open(userfile,"r")
start = 4
end = start + 100
count = start
while count != end:
for line in f.readlines()[count:(count + 2)]:
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(line))
fileout.close()
count = count + 2

Categories