user547907
user547907

Reputation:

Python text file processing

Please advice why this is does not work, and shows no errors:

def main(x, y):
    x=open('DCR.txt')
    x.read()
    print(x)
    y=open("111.txt", "a+")
    y=x
    y.close()

I'm trying to open one file and move it's content to another. 111.txt is not being created as I run the script.

Upvotes: 3

Views: 586

Answers (5)

Lerrybin
Lerrybin

Reputation: 1

your version

def main(x, y):
    x=open('DCR.txt')
    x.read() #you should assign it to a variable
    print(x)
    y=open("111.txt", "a+") 
    y=x #this line just assign the file object to y, not content
    y.close()

you can do like this:

def main():
    x=open('DCR.txt').read()
    y=open("111.txt", "a+")
    y.write(x)
    y.close()

Upvotes: 0

Mizipzor
Mizipzor

Reputation: 52351

Your code doesnt really make sense. You pass a x and a y parameter to the function but overwrite both (so why pass them in the first place?):

def main():
    x = open('DCR.txt')

You're not using the content read from the file, you have probably already seen that print(x) doesnt print the content of the file, rather in prints the file handle.

    content = x.read()

You're replacing the second file handle with the first, which really doesnt do anything since you're not using the file handles past that point (except for closing one of them). What you probably want to do is write the contents of the first file to the second:

    y.write(content)

The simplified function looks like this:

def main():
    x = open('DCR.txt')
    content = x.read()
    y = open("111.txt", "a+")
    y.write(content)

You get any errors running that?

Upvotes: 0

evotopid
evotopid

Reputation: 5429

You can't just assign a new value to an object and think it will be written to the file. Also for the other case. You have to call the right methods.

This should work:

def main(x, y):
    x=open('DCR.txt')
    content_x = x.read()
    x.close()
    print(content_x)
    y=open("111.txt", "a+")
    y.write(content_x)
    y.close()

Upvotes: 1

abesto
abesto

Reputation: 2351

If I'm not mistaken the assignment y=x simply makes the variable y point to the same file descriptor as x. It's not actually moving any data. You should call y.write( x.read() ) instead, where x.read() returns the contents of DCR.txt.

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363587

y=x does not "move content" from one file to another. It just rebinds the name (variable) y so that afterwards, it refers to the same object as x.

To copy the content from one file-like object to another, use shutil.copyfileobj:

from shutil import copyfileobj

with open('DCR.txt') as input:
    with open("111.txt", "a+") as output:
        copyfileobj(input, output)

Upvotes: 4

Related Questions