I am trying to read one file f1
, it contains numbers like this:
2
5
19
100
34
285
39
12
and I want to read this numbers, square them and write in a new file, each on new line. This is my code:
with open("Data.txt", 'r') as f1, open("Double.txt", 'w') as f2:
Lines = f1.readlines()
for new_line in Lines:
if new_line.isdigit():
x = int(new_line)
x = pow(x, 2)
on_new_line = str(x) + "\n"
f2.write(on_new_line)
but in second file it writes only
144
Can someone help me with this?
The reason the file is only returning 144 is because using readlines()
returns the line as a string, which includes the newline character at the end: \n
We can solve this by reading the file in as a whole and splitting on the newline characters to put the items in an array:
with open('data.txt', 'r') as f1, open('double.txt', 'w') as f2:
lines = f1.read().split('\n')
for new_line in lines:
squared = int(new_line)**2
f2.write(f"{squared}\n")
This will create an array with each item as a string, so on line 4, we cast that to an int in order to square it.
We also write each element to the new text file, with a newline character after it again.
You can iterate throw the file this way:
path1 = "Data.txt"
path2 = "Double.txt"
with open(path1, 'r') as f1, open(path2, 'w') as f2:
for line in f1:
try:
f2.write(str(int(line)**2))
except ValueError:
pass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.