Hi everyone

I have been trying to combine the data from two seperate text files into a new text file. The code works OK and no errors are produced, but at the join between the two files, a few lines of data are left out. The same happens at the end of the last file input too. Does anyone have any ideas what could be causing this please?
I have attached my code

a = r'C:\Documents and Settings\Matt\Desktop\Hourly Rainfall Data\organised_data\25514_1990.txt'
b = r'C:\Documents and Settings\Matt\Desktop\Hourly Rainfall Data\organised_data\25514_1991.txt'
destination = r'C:\Documents and Settings\Matt\Desktop\Hourly Rainfall Data\organised_data\test_merge\25514.txt'

open_destination_write = open(destination, 'w')
open_destination_append = open(destination, 'a')

print open_destination_write
print open_destination_append

for line in open(a).read():
	open_destination_write.write(line)

open_destination_write.close

for line in open(b).read():
	open_destination_append.write(line)

open_destination_write.close

Cheers, Matt

Recommended Answers

All 2 Replies

destination = r'[...]\test_merge\25514.txt'

open_destination_write = open(destination, 'w')
open_destination_append = open(destination, 'a')

I can't fully answer your question without an example of input and expected output; however here's my two observations.

First, you are opening the test_merge\25514.txt file twice, under two separate file handles. First in 'write' mode, then in 'append' mode. You should definitely NOT do that. Only open it once, either in append or write (depends on how you plan on using this script in the future).

for line in open(a).read():
	open_destination_write.write(line)

By doing the above you are iterating over the contents of a character by character. However your syntax suggests you meant line by line, which would be this:

for line in open(a).readlines():
    open_destination_write.write(line)

And as a final note, I suggest not using tabs in your Python code, and instead only ever use 4 spaces. Most editors can change the tab behavior in the preferences to use 4 spaces (which is the recommended indentation level for Python).

hi
this reply mite not help you in the direction of solving your problem, but i would like to give a suggestion.
It is always helpful for everyone when the subject of the thread has some detail of the doubt...helps the person who wants to help you identify ur area of doubt....and also helps the ppl having similar doubt and searching for a solution.....

Cheers...

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.