Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python文件I/O:实现复制';将一个文本文件的内容转换为空文本文件_Python_File - Fatal编程技术网

Python文件I/O:实现复制';将一个文本文件的内容转换为空文本文件

Python文件I/O:实现复制';将一个文本文件的内容转换为空文本文件,python,file,Python,File,在开始之前,我想声明我是Python的初学者。我试图创建一个名为fcopy()的函数,当复制时第二个文件不存在时,该函数将以两个文件名作为参数,并将第一个文件的内容复制到第二个文件中。然后使用函数关闭所有文件并打开第二个文件进行读取。我使用for语句读取并打印第二个文件中的行。以下是我到目前为止的情况: def fcopy(file1, file2): os.chdir('C:/Users/Noah/Documents/myPython') file1 = str(input('Enter fi

在开始之前,我想声明我是Python的初学者。我试图创建一个名为fcopy()的函数,当复制时第二个文件不存在时,该函数将以两个文件名作为参数,并将第一个文件的内容复制到第二个文件中。然后使用函数关闭所有文件并打开第二个文件进行读取。我使用for语句读取并打印第二个文件中的行。以下是我到目前为止的情况:

def fcopy(file1, file2):
os.chdir('C:/Users/Noah/Documents/myPython')
file1 = str(input('Enter file with text: '))
file2 = str(input('Enter empty file: '))
opened_file= open(file1, 'r')
for lines in file1:
    file2.write('file1')
    print(lines)

文件名作为参数传入;您不需要提示用户键入名称

def fcopy(file1, file2):
    os.chdir('C:/Users/Noah/Documents/myPython')
    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()

如果仍要测试文件2在编写时是否不存在,否则将中止,可以使用John Gordon代码中的
os.path.isfile
进行测试

def fcopy(file1, file2):
    os.chdir('C:/Users/Noah/Documents/myPython')
    if(os.path.isfile(file2)):
        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()

您的函数应该将文件名作为参数,还是应该提示用户键入文件名?在这一点上,您的描述和代码是不明确的。是的,它应该将它们作为参数,我很抱歉,我将更新问题。另外file2.write('file1')将只将'file1'写入file2。我想您是指file2.write(行)