英文:
Python3 How could i make Reading and writing using With
问题
以下是您要翻译的内容:
你好,我怎样能够在Python中同时写入和读取(使用with
)?我做了这个简单的函数来将名字添加到txt文件中,但输出通常是空的...
def student():
with open("students.txt", "w+") as my_file:
for i in range(20):
user = input("请输入你的名字:")
my_file.write(f"{user}\n")
print(my_file.read())
student()
尝试了r+
、w+
、a+
,但它们都不起作用,只有r
起作用,但那时我无法向文件添加内容。
英文:
Hello How i could make Python Write and Read at the sametime using (with) i did this simple function to add names in txt file but the output is usully empty...
def student():
with open("students.txt","w+") as my_file:
for i in range(20):
user = input("Enter your name : ")
my_file.write(f"{user}\n")
print(my_file.read())
student()
tried r+ w+ a+ but none of them were working only r works but then i can't add to the file
答案1
得分: 1
你需要将光标重新定位到文件的开头,write会将其移到文件末尾:
def student():
with open("students.txt", "w+") as my_file:
for i in range(20):
user = input("输入你的名字 : ")
my_file.write(f"{user}\n")
my_file.seek(0) # 将光标重新定位到文件开头
print(my_file.read())
student()
英文:
You need to reposition the cursor to the start of the file, write moves it to the end:
def student():
with open("students.txt", "w+") as my_file:
for i in range(20):
user = input("Enter your name : ")
my_file.write(f"{user}\n")
my_file.seek(0) # reposition cursor to start of file
print(my_file.read())
student()
答案2
得分: 0
with
语句是一种语法糖,它消除了在打开文件后关闭文件的必要性。在 Python 中,你试图写入文件的内容在文件关闭之前不会被刷新到磁盘上,直到文件关闭为止。这意味着,在上下文管理器(with
语句)中,文件仍然是打开的,而其内容为空。你可以在关闭文件后(with
语句之后)再次打开文件以读取内容,但这样效率不高。如果你只想打印出结果,请尝试以下方法:
- 在 for 循环中生成一个名字列表(不要在这里写入文件)。
- 批量将名字列表写入文件(使用
join
添加换行符)。 - 打印名字列表。
英文:
The with
statement is syntactic sugar that removes the need to close a file once opened. In Python, the contents of what you are trying to write to the file are not flushed onto the disk until the file is closed (read here). This means, that within the context manager (with
statement), the file is still open and the contents empty. You could open the file again after closing it (after the with
statement) to read the contents, but it's inefficient. If all you are trying to do is print out the result, try this:
- Generate a list of names in the for loop (don't write to the file here).
- Write list of names in bulk to the file (using
join
to add newlines). - Print list of names.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论