Jump to content

For Loop in Text File

- - - - -

  • Please log in to reply
3 replies to this topic

#1
fyo

fyo

    Newbie

  • Members
  • Pip
  • 4 posts
Hello,

I am stuck on how I can do a for loop to count up the number of nodes represented in a text file, which looks like this;

0,2,4,1,6,0,0

2,0,0,0,5,0,0

4,0,0,0,5,5,0

1,0,0,0,1,1,0

6,5,0,1,0,5,5

0,0,5,1,5,0,0

0,0,0,0,5,0,0

I want to say for each node in the file, which of course would be 7 nodes, but i'm confused as to how I go about saying it in code

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Unfortunately, your data file example is a 7x7 cube of single-digit values, which means that I don't know if you meant 7 nodes as one line is a node, or if you meant 7 nodes as one column is a node. This is important when it comes to writing an algorithm to read the data!

If it's lines, the task is rather simple:
file = open("myfile", "r")

lines = file.read().splitlines()

numNodes = len(lines)

You didn't need a for loop to count the number of lines (len() does that), but you will need a for loop to modify or read from those nodes:

for node in lines:

    #perform code here.

That's how you can work with lines easy. If it's columns you'll need something custom.
Wow I changed my sig!

#3
fyo

fyo

    Newbie

  • Members
  • Pip
  • 4 posts
Ah yes, sorry, should have made myself more clearer - i meant each digit is a node so representing the distances between nodes A and G - thanks for replying!

#4
JackomoLight

JackomoLight

    Newbie

  • Members
  • PipPipPip
  • 38 posts
Well here it is:

f = open("your_file.txt", "r") #open the file
text = f.read() #read the file
text = text.replace("\n", "") #replace the new line tag because I think we don't need it
text = text.split(",") #use split to make a list u used convinietly "," between the nodes
print(len(text)) # len the list

Simple as that. You should've dig a little in the python's reference!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users