简体   繁体   English

Python发出阅读文件

[英]Issue reading file in Python

I had some problems with my Python code.我的 Python 代码有一些问题。 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.问题 2:在我修复所有问题后,我的电脑现在好像死机了,我什至无法移动鼠标。 After freeze for a while, the code make my computer ran to BSOD.冻结一段时间后,代码使我的电脑运行到 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.好的,我想我看到问题 2 中的问题是我的文件太大了,我的服务器有 50 GB 的登录信息。 Thanks you guy for helping me solve the problem 1.谢谢大佬帮我解决问题 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.在连接文件路径时使用os.path.join()也是一个好习惯 Make sure login\info.txt does not have a backslash in front of it.确保login\info.txt前面没有反斜杠。 I printed the list afterwards to make sure it was working.之后我打印了清单以确保它能正常工作。 Windows file paths use \\ . Windows 文件路径使用\\

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.无论操作系统如何,我都建议使用pathlib模块来处理系统路径并减少操作系统路径处理中的歧义。 So, regardless of OS, an API would be (including your code):因此,无论操作系统如何, API 都是(包括您的代码):

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在此处熟悉该模块(开箱即用:): https://docs.python.org/3/library/pathlib.html

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

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