Python3 reading and writing .txt files [duplicate] - python

This question already has answers here:
What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?
(11 answers)
Closed 5 years ago.
I'm somewhat new to Python, but I have enough under my belt to know what I'm doing. What I'm trying to do is write a few lines for a .txt file (as well as a variable), and then print 5 of those characters.
import os
username = "Chad_Wigglybutt"
file = open("testfile.txt", "w")
file.write("Hello .txt file, ")
file.write("This is a test, ")
file.write("Can this write variables? ")
file.write("Lets see: ")
file.write(username)
file.close()
It then creates the file without issue, but when I add
print file.read(5)
to the code, it gives me a syntax error for file.read, and I have no clue why. I've been on the internet for a few hours now and I can't find anything. Either I'm extremely bad at google searching and I'm an idiot, or something's broken, or both. Any tips/ideas? :/

You're writing Python 3 code. In Python 3, print is a function, not a special statement. You need parentheses for function calls:
print(file.read(5))

Related

Information is not being written into file in append mode [duplicate]

This question already has answers here:
File open and close in python
(2 answers)
Closed 5 months ago.
I'm a beginner programmer in python and my lecturer wants us to make a program from scratch specifically w hard code.
It was running well previously, but when I tried testing the program earlier, this part of the program started to run an error. It said it cannot run code on a closed file. Can anyone help point out where the problem is?
Thank you so much
def temporder():
allmenu = open("allmenu.txt","r")
temporder = open("neworder.txt","a")
entry = str.upper(input("Please enter a valid product code: "))
for lines in allmenu:
code,price = lines.split(",")
if (entry in code):
temporder.write("\n" + code + "," + price)
temporder.close()
allmenu.close()
You indented the last 2 lines temporder.close() and allmenu.close(), this means that the first time it executes the if condition, it closes both files. Put the last 2 lines in the same indent level as the for loop and it should work fine.
You need to move file close statements (file.close()) to outside the for loop. Your code checks the first line of allmenu file and then closes the file.

why python read informaton in file but not it's content? [duplicate]

This question already has an answer here:
Python Read File Content [duplicate]
(1 answer)
Closed 2 years ago.
I try to Python read and then print text from file score.txt (in score.txt is text hrllo world) i write this command:
score = open("data/score.txt", "r")
print(score)
and output is:
<_io.TextIOWrapper name='data/score.txt' mode='r' encoding='cp1250'>
how can i print "hello world" from file score.txt?
You probably want to read the whole filo into the variable in your case.
score = open("data/score.txt", "r").read()
See https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
I also offer some unsolicited advice: I recommend using a so-called context manager which will automatically close the file after you're done using it (even in case reading the file fails for some reason).
with open("data/score.txt", "r") as score_file:
print(score_file.read())
This is not really very important in your case, but it is an accepted best practice and should be followed whenever possible.

problem with with-as statement as mentioned in learn python3 the hard way [duplicate]

This question already has answers here:
What is the python "with" statement designed for?
(11 answers)
Closed 4 years ago.
I've been reading the learn python3 the hard way book and in a exercise about python symbols he refers to a 'as' symbol and in the description it says "Part of the with-as statement" and the example format is "with X as Y: pass" but i couldn't find anything about such a thing online so I'm asking here.
Does anyone know anything about it?
and as a refrence it's exercise 37
The With x as y construct in python in called a context manager.
Context managers are used to properly manage resources. For example, if one is used to open a file, a context manager will ensure the file is closed.
with open('my_file.txt', 'r') as file:
for line in file:
print('{}'.format(line))
This is equivalent to:
file = open('my_file.txt') as file
for line in file:
print('{}.format(line))
file.close()
As you can see, the call to the close function is not necessary when you use a context manager.Its easy to forget to close the file, and this can lead to your system crashing if too many files are open. (There is a maximum number allowed by the operating system.)
See this link for more information and examples.

Python - print() - debugging -show file and line number [duplicate]

This question already has answers here:
filename and line number of Python script
(11 answers)
Closed 5 years ago.
When using print() in python, is it possible to print where it was called? So the output will look like var_dump in php with xdebug. Eg. I have script D:\Something\script.py, and at line 50, there is a print("sometest"), so the output will look like this:
D:\Somethinq\script.py:50 sometest
Or is there any module that could achieve this? In large projects, it's really hard to manage where these prints came from.
So, using answers provided in filename and line number of python script , this function can be called instead of print(), and prints line number before every output:
from inspect import currentframe
def debug_print(arg):
frameinfo = currentframe()
print(frameinfo.f_back.f_lineno,":",arg)

"print file.read()" Invalid Syntax in Python 3 [duplicate]

This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 7 years ago.
I wanted to create a 10 files where each file has a "blob" word at the first sentence and read those sentence directly.
Here's my code:
import random
import string
for i in range(9):
name = input('fileNumber')+ str(i+1) + '.txt'
try:
file = open(name,'w+')
file = open(name,'a')
file.write("blob")
file = open(name,'r')
print file.read() #'file' being highlighted with red color when I execute
file.close()
When I run it, I got an error message saying Invalid syntax and it highlights my file.read() line.
Can somebody tell me where's the flaw in my code?
EDIT: I'm currently using python 3.5. However, I could also switch to 2.7 as well!
Try doing this:
print(file.read())
In Python 3.x print() is a function and the parentheses are mandatory.

Categories