Python 3.5,尝试通过为一个文件定义一个函数来将一个文件的内容复制到另一个文件中

时间:2016-10-14 18:15:33

标签: python python-3.x

我通常不会在作业中寻求帮助,但我偶然发现了一个部分问题,我似乎无法做到正确。问题是:

  

编写一个函数fcopy(),它将两个文件名(作为字符串)作为输入并复制   第一个文件的内容为第二个。

到目前为止,这是我设法提出的:

def fcopy(file1, file2):
os.chdir('C:/Users/HOME/Desktop/Introduction to Computing/Lab/assignments')
open_file_1 = open(file1, 'r')
open_file_2 = open(file2, 'w')
for line in open_file_1:
    open_file_2.write(line)
open_file_1.close()
open_file_2.close()
open_file_2 = open(file2, 'r')
for line in open_file_2:
    print(line)
open_file_2.close()

通过查看许多资源,我设法到目前为止,我想知道如何使这项工作。感谢

1 个答案:

答案 0 :(得分:0)

这应该有帮助

def fcopy(file1, file2):
    #os.chdir('C:/Users/HOME/Desktop/Introduction to Computing/Lab/assignments')
    open_file_1 = open(file1, 'r')
    open_file_2 = open(file2, 'w')
    for line in open_file_1:
        open_file_2.write(line)
    open_file_1.close()
    open_file_2.close()
    open_file_2 = open(file2, 'r')
    for line in open_file_2:
        print(line)
    open_file_2.close()
fcopy("infile.txt", "outfile.txt")

这是另一种方法

def copy(infile, outfile):
    with open(infile) as file_input:
        with open(outfile, "w") as file_output:
            for line in file_input:
                file_output.write(line)
copy("infile.txt", "outfile.txt")

这种方法更好,因为它可以保证outfile将被关闭。

从infile和outfile打印内容

def fcopy(file1, file2):
    #os.chdir('C:/Users/HOME/Desktop/Introduction to Computing/Lab/assignments')
    open_file_1 = open(file1, 'r')
    open_file_2 = open(file2, 'w')
    print("-------------Infile-------------")
    for line in open_file_1:
        open_file_2.write(line)
        print(line)
    open_file_1.close()
    open_file_2.close()

    open_file_2 = open(file2, 'r')
    print()
    print("-------------Outfile-------------")
    for line in open_file_2:
        print(line)
    open_file_2.close()
fcopy("infile.txt", "outfile.txt")

def copy(infile, outfile):
    with open(infile) as file_input:
        with open(outfile, "w") as file_output:
            for line in file_input:
                file_output.write(line)

第二种方式

    with open(infile, "r") as file_in:
        print("Infile: ")
        for line2 in file_in:
            print(line2)

    print()

    with open(outfile, "r") as file_out:
        print("Outfile: ")
        for line3 in file_out:
            print(line3)            

copy("infile.txt", "outfile.txt")

我确信有更优化的方法可以做到这一点,但这是我现在可以做的。如果我找到更好的方法,我会更新我的答案。