【问题标题】:How to store input data using python3 into text file and print the data output?如何使用python3将输入数据存储到文本文件中并打印数据输出?
【发布时间】:2021-02-15 17:03:00
【问题描述】:

我对 python 完全陌生,所以我不知道我应该通过使用用户输入到文本文件中来制作数据。我所能做的就是在 input() 中使用数据变量。我尝试使用输入将数据转换为文本文件,但之后,文本文件中没有任何内容。还有什么办法可以解决吗?

import sys

def write(nameOfFile):
        name = nameOfFile+'.txt';

        file = open(name, 'w+');


        upper_code = input();
        lower_code = input();
        name_code = input();
first_code = input();
        day = input();
        date_start = input();
        date_end = input();
        hours = input();
        num_code = input();

        print(name);

        print(upper_code, lower_name);
 print(name_code, first_code);
 print(day, date_start, date_end);
 print(hours);
 print(num_code);

        return name;

if len(sys.argv)<2:
        print('usage: makefile <filename.txt>');
        print('Enter a file name: ');
        inputFi = input();
        write(inputFi);

这些是我在 python 中使用的变量:

upper_code lower_code
name_code first_code
day date_start date_end
hours
num_code

这是一个 file.txt,应该看起来像这样:

ABC abc
Rider I
TH 10/30/20 10/31/20
4
16

【问题讨论】:

    标签: python-3.x file user-input store


    【解决方案1】:

    这个怎么样?

    import sys
    
    def write(nameOfFile):
    
        with open(nameOfFile + '.txt', 'w+') as input_stream:
    
                upper_code = input('user code: ')
                lower_code = input('lower code: ')
                name_code = input('name code: ')
                first_code = input('first code: ')
                day = input('day: ')
                date_start = input('date start: ')
                date_end = input('date end: ')
                hours = input('hours: ')
                num_code = input('num code: ')
    
                print(upper_code, lower_code, file=input_stream)
                print(name_code, first_code, file=input_stream)
                print(day, date_start, date_end, file=input_stream)
                print(hours, file=input_stream)
                print(num_code, file=input_stream)
    
    if len(sys.argv)<2:
        print('usage: makefile <filename.txt>')
        print('Enter a file name: ')
        inputFi = input()
        write(inputFi)
    

    输出:

    $ python3 writetofile.py
    usage: makefile <filename.txt>
    Enter a file name: 
    file
    user code: ABC
    lower code: abc
    name code: Rider
    first code: I
    day: TH
    date start: 10/30/20
    date end: 10/31/20
    hours: 4
    num code: 16
    
    $ cat file.txt 
    ABC abc
    Rider I
    TH 10/30/20 10/31/20
    4
    16
    

    顺便说一句,您不需要在 Python 中使用分号,您可以了解有关 Python 样式指南 here 的更多信息。此外,如果您想了解更多关于在 Python 中写入和读取文件的信息,您可以阅读this

    【讨论】:

      猜你喜欢
      • 2019-01-14
      • 2020-03-29
      • 1970-01-01
      • 2020-07-04
      • 2013-12-24
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 2019-09-11
      相关资源
      最近更新 更多