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

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:

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")

Im getting this error in python: IndexError: list index out of range

Im getting is error in python for some reason i don't understand how these are outside of the index when there are 7 elements to the file
attack = user_stats.readlines()[2]
IndexError: list index out of range
this is the code:
with open(username + '.txt', 'r') as user_stats:
level = user_stats.readlines()[1]
attack = user_stats.readlines()[2]
health = user_stats.readlines()[3]
max_health = user_stats.readlines()[4]
exp = user_stats.readlines()[5]
money = user_stats.readlines()[6]
this is the txt file:
username
1
1
25
25
0
0
The first call to readlines() reads the full file and reaches the end of the file. Each subsequent call returns an empty string because you've already reached the end of the file.
There is no need to call readlines() multiple times.
well ive figured it out, idk that its the best way but it works
with open(username + '.txt', 'r') as user_stats:
level = user_stats.readlines()[1]
with open(username + '.txt', 'r') as user_stats:
attack = user_stats.readlines()[2]
with open(username + '.txt', 'r') as user_stats:
health = user_stats.readlines()[3]
with open(username + '.txt', 'r') as user_stats:
max_health = user_stats.readlines()[4]
with open(username + '.txt', 'r') as user_stats:
exp = user_stats.readlines()[5]
with open(username + '.txt', 'r') as user_stats:
money = user_stats.readlines()[6]
Firstly, as person above said the code should look something like that
with open('username.txt', 'r') as user_stats:
lines = user_stats.readlines()
level = lines[1]
attack = lines[2]
health = lines[3]
max_health = lines[4]
exp = lines[5]
money = lines[6]
print(username, level, attack, health, max_health, exp, money) #print to check if everything is right
Secondly, such things as stats should be stored inside objects but from what i can remember there are some limitations to python constructors, so i cannot really help much here.
more about constructors

TypeError: cannot concatenate 'str' and 'NoneType' objects?

I have this large script ( I will post the whole thing if I have to but it is very big) which starts off okay when I run it but it immediatly gives me 'TypeError: cannot concatenate 'str' and 'NoneType' objects' when it comes to this last bit of the code:
with open("self.txt", "a+") as f:
f = open("self.txt", "a+")
text = f.readlines()
text_model = markovify.Text(text)
for i in range(1):
tool = grammar_check.LanguageTool('en-GB')
lin = (text_model.make_sentence(tries=800))
word = ('' + lin)
matches = tool.check (word)
correct = grammar_check.correct (word, matches)
print ">",
print correct
print ' '
f = open("self.txt", "a+")
f.write(correct + "\n")
I have searched everywhere but gotten nowhere. It seems to have something to do with: word = ('' + lin). but no matter what I do I can't fix it. What am I doing wrong?
I'm not sure how I did it but with a bit of fiddling and google I came up with a solution, the corrected code is here (if you're interested):
with open("self.txt", "a+") as f:
f = open("self.txt", "a+")
text = f.readlines()
text_model = markovify.Text(text)
for i in range(1):
tool = grammar_check.LanguageTool ('en-GB')
lin = (text_model.make_sentence(tries=200))
matches = tool.check (lin)
correct = grammar_check.correct (lin, matches)
lowcor = (correct.lower())
print ">",
print str (lowcor)
print ' '
f = open("self.txt", "a+")
f.write(lowcor + "\n")
Thanks for all the replies, they had me thinking and that's how I fixed it!
You can't concatenate a string and a NoneType object. In your code, it appears your variable lin is not getting assigned the value you think it is. You might try an if block that starts like this:
if type(lin) == str:
some code
else:
raise Exception('lin is not the correct datatype')
to verify that lin is the correct datatype before printing.

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()

Python File errors

File = input("Please enter the name for your txt. file: ")
fileName = (File + ".txt")
WRITE = "w"
APPEND = "a"
file = []
name = " "
while name != "DONE" :
name = input("Please enter the guest name (Enter DONE if there is no more names) : ").upper()
fileName.append(name)
fileName.remove("DONE")
print("The guests list in alphabetical order, and it will save in " + fileName + " :")
file.sort()
for U in file :
print(U)
file = open(fileName, mode = WRITE)
file.write(name)
file.close()
print("file written successfully.")
I am just practicing to write the file in Python, but something bad happened.
Here are still some errors about this:
fileName.remove("DONE")
Still showing 'str' error.
filename=filename+name
Use the above code
Python strings are immutable. Therefore you can't use append() on them. Use += instead:
fileName += name
which is shorthand for
fileName = fileName + name
Note how nothing is appended to the string, instead a new one is created and then assigned to fileName.
Try this.
I thought you have some mistaken in variable name.
aFile = input("Please enter the name for your txt. file: ")
fileName = (aFile + ".txt")
WRITE = "w"
APPEND = "a"
file = []
name = " "
while name != "DONE" :
name = input("Please enter the guest name (Enter DONE if there is no more names) : ").upper()
file.append(name)
file.remove("DONE")
print("The guests list in alphabetical order, and it will save in " + fileName + " :")
file.sort()
for U in file :
print(U)
outputfile = open(fileName, mode = WRITE)
outputfile.write(name)
outputfile.close()
print("file written successfully.")
Just right out the bat, you can not append to a toople.
fileName.append(name) #how can you append or remove anything into or from this when it contains toople?
Another thing, I don't know what version of python you are using but, I never seen expression like this
file = open(fileName, mode = WRITE) #this should be something like (file=open(fileName,"w"))
Just overall check your code. Like I said you can not add or remove stuff from a toople; only in lists and dictionaries.
append is the list's method where as fileName declared in your code is treated as string. If your intention is to append the string to file, open the file in "append" mode and write to it:
with open(aFile + ".txt", "a") as f:
f.write("appended text")

Categories