64.4k views
5 votes
A file named data.txt contains an unknown number of lines, each consisting of a single integer. Write some code that creates two files, dataplus.txt and dataminus.txt, and copies all the lines of data1.txt that have positive integers to dataplus.txt, and all the lines of data1.txt that have negative integers to dataminus.txt. Zeros are not copied anywhere.

User Zout
by
5.2k points

2 Answers

5 votes

Answer:

I am doing it with python.

Step-by-step explanation:

nums = '9 -8 -7 -6 -5 -4 -2 0 1 5 9 6 7 4'

myfile = open('data.txt', 'w')

myfile.write(nums)

myfile.close()

myfile = open('data.txt', 'r')

num1 = (myfile.read())

num1 = num1.split()

print(num1)

print(type(num1))

for x in num1:

x = int(x)

if x < 0:

minus = open('dataminus.txt', 'a')

minus.write(str(x) + ' ')

minus.close()

elif x>= 0:

plus = open('dataplus.txt', 'a')

plus.write(str(x)+' ')

plus.close()

User Simonbs
by
5.9k points
3 votes

Answer:

#section 1

data = open('data.txt', 'r')

num = (data.read())

num = num.split()

data.close()

#section 2

for x in num:

x = int(x)

if x < 0:

minus = open('dataminus.txt', 'a')

minus.write(str(x) + ' ')

minus.close()

elif x > 0:

plus = open('dataplus.txt', 'a')

plus.write(str(x)+' ')

plus.close()

Step-by-step explanation:

#section 1

A file data.txt containing an unknown number of lines each containing a single integer is opened.

The data is read from it and split to form a list from which the code will iterate over with a FOR loop and some conditional statements will be used to determine if the number is positive or negative.

#section 2

In this section two new files are created/ opened dataplus.txt and dataminus.txt and all the positive integers are stored in the dataplus.txt and the negative integers in the dataminus.txt.

The IF statement and elif statement used ensures that zero(0) is not captured ensuring that the code fulfills all the requirements in your question.

User Gavin Smith
by
5.2k points