简体   繁体   中英

Issue reading file in Python

I had some problems with my Python code. My code:

import os
logininfo = list()
with open(os.getcwd() + '/login/info.txt', 'r') as f:
     logininfo = f.readlines()

But my code isn't work, so how do I fix that?

Edit: I changed the quote and changed the ' to '

Problem 2: After I fix all that look like my computer is freeze now and I can't even move my mouse. After freeze for a while, the code make my computer ran to BSOD. What happened?

Okay, I think I see what the problem in problem 2 that my file was too big with 50 GB of login information of my server. Thanks you guy for helping me solve the problem 1.

Your problem is likely that your / (forward slashes) are supposed to be \ (backslashes). It is also a good practice to use os.path.join() when concatenating file paths. Make sure login\info.txt does not have a backslash in front of it. I printed the list afterwards to make sure it was working. Windows file paths use \\ .

import os
with open(os.path.join(os.getcwd(), 'login\info.txt'), 'r') as f:
    logininfo = f.readlines()
print(logininfo)

I believe the wrong thing is that you're using double slashs, when it should be:

import os

with open(os.getcwd() + ‘/login/info.txt’, 'r') as f:
     logininfo = f.readlines()

I reproduced the error here, created a file with the same folder structure as yours, and this definitely should work:

In [3]: with open(os.getcwd() + '/login/info.txt', 'r') as f:
   ...:     lines = f.readlines()
   ...:     for line in lines:
   ...:         print(line)
   ...: 
Olá,



deixa eu ver esse erro aqui

Regardless of OS, I would recommend using pathlib module to deal with system paths and to decrease ambiguity in OS path handling. So, regardless of OS, an API would be (including your code):

from pathlib import Path

file_path = Path.cwd() / 'login' / 'info.txt'

with open(file_path, 'r') as f:
    login_info = f.readlines()

Get familiar with that module (it's out of the box:) here: https://docs.python.org/3/library/pathlib.html

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.

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