Skip to main content
 首页 » 编程设计

python之读/写文件问题

2025年05月04日11bluestorm

我一直试图将一个长文本从一个文件复制到另一个文件,但它总是只复制了一小部分。它看起来像一个我可以解决的极限问题。

如果有人能帮助我或解释我的错误,我会很高兴。

def runMenu(): 
 
print "\nMENU" 
print "  1) Copiar" 
print "  0) Exit" 
 
response = int( raw_input().strip() ) 
 
if response == 1: 
    print "Copiar"        
    try: 
 
        archivo=open("D:\Boot.txt","r") 
        print "Name of the file: ", archivo.name 
        print "Closed or not : ", archivo.closed 
        print "Opening mode : ", archivo.mode 
 
        print "--------ORIGEN-----------" 
        print archivo.read() 
        print "-------------------------" 
        archivo.seek(0, 0) 
 
 
        archivo2=open("D:\Copia.txt","w+") 
        print "Name of the file: ", archivo2.name 
        print "Closed or not : ", archivo2.closed 
        print "Opening mode : ", archivo2.mode 
 
 
 
        archivo2.write(archivo.read()) 
 
        archivo2.seek(0, 0) 
        print "---------DESTINO---------" 
        print archivo2.read() 
        print "-------------------------" 
        archivo.close() 
        archivo2.close() 
 
    except IOError: 
        print ("I/O Error de Lectura") 
    else: 
        print "Lectura OK" 
 
elif response == 0: 
    #device.close() 
    print "Exit" 
 
return response 
 
def main(): 
    print "main" 
    while(1): 
        if runMenu() == 0: break 
 
main() 

请您参考如下方法:

使用shutil.copy()

http://docs.python.org/library/shutil.html#shutil.copy

shutil.copy(src, dst)

Copy the file src to the file or directory dst. If dst is a directory, a file with the same basename as src is created (or overwritten) in the directory specified. Permission bits are copied. src and dst are path names given as strings.

-Sunjay03