Jump to content

Python import data form file

Go to solution Solved by vorticalbox,

So to solve this problem I changed the file to have each line like this

Quote

Ben,123456

Bill,654321

I then loaded the file with

with open(file) as f:
    for line in f:
        line = line.strip()
        currentline = line.split(',')
        info = {'name': currentline[0], 'number': currentline[1]}
        dict.append(info)

then saved the file

def save():
    f = open(file,'w')
    for i in dict:
        f.write('{},{}'.format(i['name'],i['number']))
    f.close()

 

So I am trying to create a simple phonebook just to get back into python. Right now I have a list with the each item a dictionary and this works just fine. I then save the data to a file

{'number': '123456', 'name': 'ben'}
{'number': '654321', 'name': 'bill'}

and the list prints out like this.

Quote

[{'number': '123456', 'name': 'bill'}, {'number': '654321', 'name': 'ben'}]

but when I read from the file after saving it now prints like this when I print on load() but is [] when using the function

["{'number': '123456', 'name': 'ben'}"]
["{'number': '654321', 'name': 'bill'}"]

Which now no longer works in my script, whole code below

 

Spoiler

import os
list = []
file = 'data.txt'


def numbers():
    cls()
    print(list)
    input('press enter to continue')


def add():
    cls()
    name = input('Enter name: ')
    number = input('Enter number: ')
    info = {'name': name, 'number': number}
    list.append(info)
    print('{} Added to phonebook'.format(name))
    input('press enter to continue')


def save():
    f = open(file,'w')
    for i in list:
        f.write('%s\n' % i)
    f.close()


def load():
    f = open(file, 'r')
    for line in f.readlines():
        list.append(line.splitlines())


def menu():
    cls()
    print('1. List all')
    print('2. Add')
    print('x. Exit')


def cls():
    os.system('cls' if os.name=='nt' else 'clear')
load()
while True:
    menu()
    choice = input('Enter choice: ')
    if choice == '1':
        numbers()
    elif choice == '2':
        add()
    elif choice == 'x':
        save()
        break
    else:
        print('Invalid input')

 

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
https://linustechtips.com/topic/646599-python-import-data-form-file/
Share on other sites

Link to post
Share on other sites

Perhaps something like this

Spoiler

import os
file = 'data.txt'

def numbers():
    #cls()
    print(lists)
    input('press enter to continue')


def add():
    #cls()
    name = input('Enter name: ')
    number = input('Enter number: ')
    info = {'name': name, 'number': number}
    lists.append(info)
    print('{} Added to phonebook'.format(name))
    input('press enter to continue')


def save():
    f = open(file,'w')
    for i in lists:
        f.write('%s\n' % i)
    f.close()

def menu():
    #cls()
    print('1. List all')
    print('2. Add')
    print('x. Exit')


def cls():
    os.system('cls' if os.name=='nt' else 'clear')
#start and load
with open(file) as f:
    lists = f.read().splitlines()

while True:
    menu()
    choice = input('Enter choice: ')
    if choice == '1':
        numbers()
    elif choice == '2':
        add()
    elif choice == 'x':
        save()
        break
    else:
        print('Invalid input')

 

                     .
                   _/ V\
                  / /  /
                <<    |
                ,/    ]
              ,/      ]
            ,/        |
           /    \  \ /
          /      | | |
    ______|   __/_/| |
   /_______\______}\__}  

Spoiler

[I5-12600k | 32gb DDR5 6000 | RTX5070 | 2x1tb M.2]

 

[Ryzen 5 1600 | 16gb DDR4 3200 | GTX1030 | 4x 8tb HDD] 

 

Link to post
Share on other sites

still gives a blank list

 

Spoiler

1. List all
2. Add
x. Exit
Enter choice: 1
[]
press enter to continue

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites

24 minutes ago, vorticalbox said:

still gives a blank list

Did you add contacts to the file first? Its working for me

Spoiler

1. List all
2. Add
x. Exit
Enter choice: 1
[]
press enter to continue
1. List all
2. Add
x. Exit
Enter choice: 2
Enter name: Kevin
Enter number: 666
Kevin Added to phonebook
press enter to continue
1. List all
2. Add
x. Exit
Enter choice: 1
[{'name': 'Kevin', 'number': '666'}]
press enter to continue

The only other thing I can think of is to check that you can write to the directory and that the file isn't being used in another program. Perhaps check that 

[For future reference] Don't name a list "list" as it can create issues with the list function in python

                     .
                   _/ V\
                  / /  /
                <<    |
                ,/    ]
              ,/      ]
            ,/        |
           /    \  \ /
          /      | | |
    ______|   __/_/| |
   /_______\______}\__}  

Spoiler

[I5-12600k | 32gb DDR5 6000 | RTX5070 | 2x1tb M.2]

 

[Ryzen 5 1600 | 16gb DDR4 3200 | GTX1030 | 4x 8tb HDD] 

 

Link to post
Share on other sites

3 minutes ago, RedWulf said:

Did you add contacts to the file first? Its working for me

  Reveal hidden contents

1. List all
2. Add
x. Exit
Enter choice: 1
[]
press enter to continue
1. List all
2. Add
x. Exit
Enter choice: 2
Enter name: Kevin
Enter number: 666
Kevin Added to phonebook
press enter to continue
1. List all
2. Add
x. Exit
Enter choice: 1
[{'name': 'Kevin', 'number': '666'}]
press enter to continue

The only other thing I can think of is to check that you can write to the directory and that the file isn't being used in another program. Perhaps check that 

[For future reference] Don't name a list "list" as it can create issues with the list function in python

noted, yeah I have the contacts in the file. I moved the load part form a function and into the main part and it now works just fine ty :) seems it didn't like load()

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites

@RedWulf having a problem again :( so now I want to print who is on on each line i tried this

 

def numbers():
    #cls()
    for i in dict:
        print(i['name'], i['number'])
    input('press enter to continue')

but i am getting 

 

Quote

Traceback (most recent call last):
  File "D:\Aaron\Documents\Projects\test.py", line 46, in <module>
    numbers()
  File "D:\Aaron\Documents\Projects\test.py", line 9, in numbers
    print(i['name'], i['number'])
TypeError: string indices must be integers

However If i have an empty file at the start and add the contacts to the list that way this code works fine.

Quote

1. List all
2. Add
x. Exit
Enter choice: 1
bill 123456
ben 654321
press enter to continue

I am assuming my load is adding them to the list as a long string rather than as a directory 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites

So to solve this problem I changed the file to have each line like this

Quote

Ben,123456

Bill,654321

I then loaded the file with

with open(file) as f:
    for line in f:
        line = line.strip()
        currentline = line.split(',')
        info = {'name': currentline[0], 'number': currentline[1]}
        dict.append(info)

then saved the file

def save():
    f = open(file,'w')
    for i in dict:
        f.write('{},{}'.format(i['name'],i['number']))
    f.close()

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×