如何使用Python打开和读取输入文件并将其打印到输出文件?

时间:2019-02-23 04:01:52

标签: python file input output

那么我该如何要求用户为我提供输入文件和输出文件? 我希望用户提供的输入文件中的内容可以打印到用户提供的输出文件中。在这种情况下,用户可以输入

Enter the input file name: copyFrom.txt
Enter the output file name: copyTo.txt
输入文件中的

只是文本"hello world"

谢谢。请尽可能保持简单

5 个答案:

答案 0 :(得分:1)

如果您只想复制文件,shutil的复制文件将隐式执行循环:

import os
from shutil import copyfile

openfile = input('Enter the input file name:')
outputfile = input('Enter the output file name:')

copyfile(openfile, outputfile)

此帖子How do I copy a file in Python?了解更多详情

答案 1 :(得分:0)

您可以执行此操作...

import os
openfile = input('Enter the input file name:')
outputfile = input('Enter the output file name:')
if os.path.isfile(openfile):
    file = open(openfile,'r')
    output = open(outputfile,'w+')
    output.write(file.read())
    print('File written')
    exit()
print('Origin file does not exists.')

答案 2 :(得分:0)

首先,您必须读取文件并将其保存到某个变量(此处为rd_data):

if os.path.exists(input_file_name):
        f = open(input_file_name,"r")
        rd_data = f.read()
        f.close()

然后,您必须将变量写入其他文件:

f = open(output_file_name,"w")
f.write(rd_data)
f.close()

完整代码如下:

import os

input_file_name = input("Enter file name to read: ")
output_file_name = input("Enter file name to write: ")
if os.path.exists(input_file_name):
    f = open(input_file_name,"r")
    rd_data = f.read()
    f.close()

f = open(output_file_name,"w")
f.write(rd_data)
f.close()

答案 3 :(得分:0)

这是一个应该在Python3中工作的示例。输入和输出文件名需要包含完整路径(即“ /foo/bar/file.txt”

import os
input_file = input('Enter the input file name: ')
output_file = input('Enter the output file name: ')

def update_file(input_file, output_file):
    try:
        if os.path.exists(input_file):
            input_fh = open(input_file, 'r')
            contents = input_fh.readlines()
            input_fh.close()
            line_length = len(contents)
            delim = ''
            if line_length >= 1:
                formatted_contents = delim.join(contents)
                output_fh = open(output_file, 'w')
                output_fh.write(formatted_contents)
                output_fh.close()
            print('Update operation completed successfully')
    except IOError:
        print(f'error occurred trying to read the file {input_fh}')

update_file(input_file, output_file)

答案 4 :(得分:0)

要输入输入文件名和输出文件名,只需使用input(s)函数,其中s是输入消息。

要获取“用户提供的输入文件中的内容以打印到输出文件中”,这意味着读取输入文件并将读取的数据写入输出文件中。

要读取输入文件,请使用f = open(input_filename, 'r'),其中第一个参数是文件名,第二个参数是打开模式,其中'r'表示已读取。然后让readtext为输入文件的读取文本信息,使用readtext = f.read():这将返回f的全部文本内容。

要将读取的内容输出到输出文件,请使用g = open(output_filename, 'w'),请注意,现在第二个参数是'w',表示写入。要写入数据,请使用g.write(readtext)

请注意,如果找不到输入文件或输出文件无效或目前无法实现,则会引发异常。要处理这些异常,请使用try-except块。

这实际上是Python中的文件复制操作。 shutil可以作为一种有用的选择。

相关问题