简体   繁体   中英

How to replace values in another file based on user input using dictionary?

I want to take input from user for orgname, username, password and replace values in below mentioned Sample.py file. Sample file:

try:
   functions.set_values(orgname='Sample', username='Sample1', password='xyz')
except:
   bail('test failed')

Here is what I have written:

while True:
    try:
        org_data = {}
        orgname = str(input('Enter orgname: '))
        username = str(input('Enter username: '))
        password = str(input('Enter password: '))

        org_data[orgname] = orgname
        org_data[username] = username
        org_data[password] = password

        break

    except ValueError:
        print('Invalid Input. Try again.')

src_file = open('Sample.py', "rt")
dest_file = open(f'Sample_{orgname}.py', "wt")
for line in src_file:
    for key,value in org_data:
        dest_file.write(line.replace(key, value))
src_file.close()
dest_file.close()

I get the below error:

Traceback (most recent call last):
  File "./replace_org.py", line 44, in <module>
    for key,value in org_data:
ValueError: too many values to unpack (expected 2)

part of the reason could be, you are unpacking a dictionary so you need to access the.items()

src_file = open('Sample.py', "rt")
dest_file = open(f'Sample_{orgname}.py', "wt")
for line in src_file:
    for key,value in org_data.Items(): #<---- unpack the values like this
        dest_file.write(line.replace(key, value))
src_file.close()
dest_file.close()

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