简体   繁体   English

在python中创建一个新的INI文件

[英]Create a new INI-file in python

I need to create a function within my code which does the following:我需要在我的代码中创建一个函数,它执行以下操作:

  1. creates a new ini-file to the same location path where my code is (example: C:\\Users<user name>\\source\\repos创建一个新的 ini 文件到我的代码所在的相同位置路径(例如:C:\\Users<user name>\\source\\repos
  2. I want it to ask [username], [organisation], [server], [port] and [filename] -> save/overwrite it to path我想让它询问 [用户名]、[组织]、[服务器]、[端口] 和 [文件名] -> 将其保存/覆盖到路径

So i want it to start like this, but I have no idea how to write it to a new file所以我希望它像这样开始,但我不知道如何将其写入新文件

### create a function that creates new file according to user input and save it to directory

def Osio8():   
    print ("Create new INI file \n")   
    
    ## asks for user input
    input_name = str(input("Give user name:" ))
    input_organization = str(input("Organisation name: "))
    input_server = str(input("Server IP address: "))
    input_port = str(input("Port number: "))
    input_file = str (input("File name:" ))
    fo = open (input_file, "w")


    ## writes the information to the file
    fo.write = multi_line_string = ("; last modified 1 April 2001 by John    Doe\n"
    "[owner]\n"
    "name=" + input_name + "\n"
    "organization=" + input_organization + "\n"
    "\n"
    "[database]\n"
    "; use IP address in case network name resolution is not working\n"
    "server=" + input_server + "\n"
    "port=" + input_port + "\n"
    "file='" + input_file + "'\n")

Currently this creates a new file with given file name, but nothing is stored.目前,这会创建一个具有给定文件名的新文件,但不会存储任何内容。 What am I doing wrong?我究竟做错了什么?

首先,询问用户所需的文件名,只有在收到答案后才以所需的模式打开文件(可能是“w”)所有这些,然后才使用open()

You can use configparser .您可以使用configparser

#!/usr/bin/env python3

import configparser

def Osio8():
    print('Create new INI file')

    input_config_file = input('Config file name: ')

    input_name = input('User name: ')
    input_organization = input('Organisation name: ')
    input_server = input('Server IP address: ')
    input_port = input('Port number: ')
    input_file = input('File name: ')

    config = configparser.ConfigParser(allow_no_value=True)
    config.optionxform = str

    config.add_section('owner')
    config.set('owner', '; last modified 1 April 2001 by John Doe', None)
    config['owner']['name'] = input_name
    config['owner']['organization'] = input_organization

    config.add_section('database')
    config.set('database', '; use IP address in case network name resolution is not working', None)
    config['database']['server'] = input_server
    config['database']['port'] = input_port
    config['database']['file'] = input_file

    with open(input_config_file, 'w') as configfile:
        config.write(configfile)

if __name__ == '__main__':
    Osio8()
$ ./so64756020.py
Create new INI file
Config file name: newconfig.ini
User name: Test user name
Organisation name: Test org name
Server IP address: 1.2.3.4
Port number: 1234
File name: Test file name

$ cat newconfig.ini
[owner]
; last modified 1 April 2001 by John Doe
name = Test user name
organization = Test org name

[database]
; use IP address in case network name resolution is not working
server = 1.2.3.4
port = 1234
file = Test file name 

EDIT (based on the comment of not being "allowed" to use configparser ):编辑(基于不被“允许”使用configparser ):

You will have then to create the file contents "manually" (which is fine as an exercise, but likely for nothing else beyond that).然后,您将不得不“手动”创建文件内容(作为练习很好,但可能除此之外别无其他)。

#!/usr/bin/env python3
  
import configparser

def Osio8():
    print('Create new INI file')

    input_config_file = input('Config file name: ')

    input_name = input('User name: ')
    input_organization = input('Organisation name: ')
    input_server = input('Server IP address: ')
    input_port = input('Port number: ')
    input_file = input('File name: ')

    contents = f"""[owner]
; last modified 1 April 2001 by John Doe
name = {input_name}
organization = {input_organization}

[database]
; use IP address in case network name resolution is not working        
server = {input_server}
port = {input_port}
file = {input_file}
"""

    with open(input_config_file, 'w') as configfile:
        configfile.write(contents + '\n')

if __name__ == '__main__':
    Osio8()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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