如何打开和读取输入文件,并用Python将其打印到输出文件?
那么,我如何要求用户向我提供输入文件和输出文件呢? 我希望用户提供的输入文件中的内容打印到用户提供的输出文件中。在这种情况下,用户将在如何打开和读取输入文件,并用Python将其打印到输出文件?,python,file,input,output,Python,File,Input,Output,那么,我如何要求用户向我提供输入文件和输出文件呢? 我希望用户提供的输入文件中的内容打印到用户提供的输出文件中。在这种情况下,用户将在 Enter the input file name: copyFrom.txt Enter the output file name: copyTo.txt 输入文件中只有文本“hello world” 谢谢。如果可能的话,请尽可能保持简单。您可以这样做 import os openfile = input('Enter the input file name
Enter the input file name: copyFrom.txt
Enter the output file name: copyTo.txt
输入文件中只有文本“hello world”
谢谢。如果可能的话,请尽可能保持简单。您可以这样做
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.')
首先,您必须读取文件并将其保存到某个变量(此处
rd_data
):
然后必须将变量写入其他文件:
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()
下面是一个应该在Python3中工作的示例。输入和输出文件名需要包含完整路径(即“/foo/bar/file.txt”
如果只想复制文件,则shutil的复制文件隐式执行循环:
import os
from shutil import copyfile
openfile = input('Enter the input file name:')
outputfile = input('Enter the output file name:')
copyfile(openfile, outputfile)
这篇文章详细介绍了输入文件和输出文件名,只需使用
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
可以作为有用的替代方法。您还可以编写一个条件来检查输出文件是否已经存在;如果已经存在,则将输入文件的内容附加到输出文件。不需要条件,output=open(outputfile,'w+')
可以。没有看到,我的错!这只适用于从输入文件读取一行并将其写入输出文件。请尝试按照问题中的要求对文件的整个内容执行此操作:)@AshutoshPathak good point!根据copyFrom文件的不同,我更新了一行或多行内容。此答案可能与常见问题的答案重复。
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)
import os
from shutil import copyfile
openfile = input('Enter the input file name:')
outputfile = input('Enter the output file name:')
copyfile(openfile, outputfile)