Hi, I write some data to a file called original.txt in python, then i read the file original.txt ,convert watever in the file to string(str), then write it in another file called copy.txt. Now i want to read the copy.txt and output it in python itself. It does not display nothing.Why this?

rfile = open('original.txt', "r")
char=infile.read()
print"Text in file:",char

for i in char:
     x=open('copy.txt','a')
     x.write(str(i))

rfile1 = open('copy.txt', "r")
abc=infile.readlines()
print"Data in file copy:",abc

I don't know what this variable infile is, but it's not rfile nor rfile1. In the same way, why do you read the first file with read() and the last one with readlines() ? The 2 functions return different datatypes. Files are better opened with the with construct:

with open('original.txt', 'rb') as infile:
    content = infile.read() # content is now an instance of 'str'

with open('copy.txt', 'wb') as outfile:
    outfile.write(content)

with open('copy.txt', 'rb') as infile:
    content2 = infile.read()

print "check if copies are the same: ", content == content2

After each with block, the file is properly closed. The 'b' in the opening mode is better in some OSes. It does nothing in other OSes.

ok thx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.