简体   繁体   中英

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 addperson and 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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM