0

Even though it in the same directory as the Python file it cannot be red

from datetime import datetime

infile = r"./system.log.txt"
logFile = []
def readLog():
        
    with open(infile) as f:
        f = f.readlines()

    for line in f:
        temp= line.split('\n')
        logFile.append(temp[0])


def show():

    for line in logFile:
        print(line)
  • 1
    This issue may occurs when you are running the .py file from a different directory. Try to `cd` into the same .py file and the logs file directory and run the .py file using `python fileName.py` – Kasper Aug 23 '20 at 11:05
  • 1
    you dont need the `./` i guess . just try `with open('system.log.txt') as f` – Sowjanya R Bhat Aug 23 '20 at 11:06
  • The system doesn't care which directory your script is in; it cares what your current working directory is when you start the script. Maybe see also [Difference between `./` and `~/`](https://stackoverflow.com/a/55342466/874188) – tripleee Aug 23 '20 at 11:10
  • As an aside, if you read the lines with `readlines()` there is no way that any of the lines can contain an embedded line break. – tripleee Aug 23 '20 at 11:12

2 Answers2

1

I am assuming you have this sructure
folder
|--sys.log.txt
|--main.py

cd folder then python main.py

file='system.log.txt'
with open(file,'r') as f:
    print(f.read())
user13966865
  • 448
  • 4
  • 13
0

Check the path of your file against what gets printed from the code below.

import os
print(os.path.dirname(__file__) + "/system.log.txt")

Also for loop needs to be indented properly.

import os

infile = os.path.dirname(__file__) + "/system.log.txt"
logFile = []

def readLog():
    with open(infile) as f:
        f = f.readlines()

        for line in f:
            temp= line.split('\n')
            logFile.append(temp[0])
Abhilash
  • 2,026
  • 17
  • 21