应该是一道简简单单的python

  1. Write a program that prompts for two file names and exchanges the contents of thetwo files. Your program should be sufficiently robust that if a file doesn't exist, theprogram will reprompt.

你题目的解答代码如下:

name1 = input("请输入文件名1:")
name2 = input("请输入文件名2:")
try:
    with open(name1, 'r', encoding='utf-8') as fileObj:
        data1 = fileObj.read()
    with open(name2, 'r', encoding='utf-8') as fileObj:
        data2 = fileObj.read()
    with open(name1, 'w', encoding='utf-8') as fileObj:
        fileObj.write(data2)
    with open(name2, 'w', encoding='utf-8') as fileObj:
        fileObj.write(data1)
except FileNotFoundError:
    print("文件不存在")

如有帮助,望采纳!谢谢!

代码可这样写:

import os
dir = r"F:\2021\qa\testing"
while 1:
    f1=input('file1 name:')
    f2=input('file2 name:')
    a=f1 in os.listdir(dir)
    b = f2 in os.listdir(dir)
    if a and b:
        break
with open(dir+'/'+f1,'r') as fa,open(dir+'/'+f2,'r') as fb:
    fr1=fa.read()
    fr2=fb.read()
with open(dir+'/'+f1, 'w') as fc, open(dir+'/'+f2, 'w') as fd:
    fc.write(fr2)
    fd.write(fr1)


如有帮助,请点击采纳按钮。