简体   繁体   English

在文件的新行上写入数字

[英]Writing numbers in file on new lines

I am trying to read one file f1 , it contains numbers like this:我正在尝试读取一个文件f1 ,它包含如下数字:

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文件只返回 144 的原因是因为使用readlines()将行作为字符串返回,其中包括末尾的换行符: \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.这将创建一个数组,其中每个项目都作为一个字符串,所以在第 4 行,我们将它转换为一个 int 以使其平方。

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:您可以通过这种方式迭代 throw 文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM