0

I am writing a program that can divide with /2 from a txt file python

So in this code op will read the content of txt

with open("python/file/t.txt") as txt:
    op = txt.read()
   
    def div():
        divide = int(op)/2
        print(divide)
div()

But it is showing me a error:

ValueError: invalid literal for int() with base 10: '1\n2\n3\n4\n5\n6\n7\n8\n9\n10'

My t.txt file has 1 to 10 arranged vertically.

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 2
    Does this answer your question? [Iterate through a file lines in python](https://stackoverflow.com/questions/48124206/iterate-through-a-file-lines-in-python) – Nick ODell Jun 01 '23 at 19:11
  • 1
    your input is newline delimited. Use a for loop over `op.split("\n")` – JonSG Jun 01 '23 at 19:11

1 Answers1

3

When you call read() you are getting back the entire contents of the file. The text of the numbers and the newline characters. To process each number (one per line) you would want to split op on the newline character "\n".

Something like:

with open("in.txt", "r") as file_in:
    for row in file_in.read().split("\n"):
        print(int(row) / 2)        

Note that split() would also be valid as the default behavior is split() to do so on whitespace including line breaks and tabs.

However, this is such a common thing python allows one to simplify this to:

with open("in.txt", "r") as file_in:
    for row in file_in:
        print(int(row) / 2)

Either will give you back:

0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0

Addendum:

Per the OP, the use of readlines() also fits the bill here and I will pull their comment into this answer for clarity.

with open("in.txt") as file_in:
    for row in file_in.readlines():
        print(int(row) / 2)        
JonSG
  • 10,542
  • 2
  • 25
  • 36
  • 1
    Thx well I figured it out by myself `with open("python/file/t.txt") as txt: op = txt.readlines() save = [] for line in op: div = int(line)/2 print(div) ` – NUKE NOM Jun 01 '23 at 19:36
  • `readlines()` does much the same and is a fine alternative. You might not need the `save = []` though – JonSG Jun 01 '23 at 19:38
  • I have a question from where does this \n come from it is a text file and i have stored numbers vertically does it have a relation with ascii – NUKE NOM Jun 01 '23 at 19:43
  • the newline character(s) `"\n"` and in windows `"\r\n"` and handled in python as simply `"\n"` are control characters that can appear in strings indicating that when displayed a newline should be rendered. They are the content in your file that allows your numbers to render "vertically". Tab characters `"\t"` are a second example. They do appear in the ASCII encoding but they are also appear in (almost?) every other encoding in some form. – JonSG Jun 01 '23 at 19:59