Open and print the contents of a file? - python

I am trying to write a program that will open a file and print its contents. I am having some trouble with defining it I suppose? If it is not telling me that "path" is not defined, then it is telling me that "new_dir" is not defined.
Here is the code:
import pathlib
def prog_info():
print("This program will open a file, read and print its contents.")
print("-----------------------------------------------------------")
prog_info()
file_path = new_dir / "numbers.txt"
file_path.parent.mkdir()
file_path.touch()
with path.open("numbers.txt", mode="r", encoding="utf-8") as file:
for line in file:
print(line.strip())
The file is going to have three numbers that will be printed:
22
14
-99

with open("filename or location", 'r') as my_file:
for line in my_file:
print(line)
I hope this helped you.
You don't need mode, and you don't need the import. All you need is the code provided

Related

Print in external files with FOR and getting blank txt files

In that part of code I make the files txt and its working
import sys
for i in range(6):
file = open('teste{:d}.txt'.format(i), 'a')
sys.stdout = file
And now the problem, the files were created but in this part of code it didnt work, i can compile but the files are empty
for i in range(1,6):
f=open('100K_Array_{:d}.txt'.format(i), 'r')
alist = f.readlines()
quickSort(alist)
print(alist)
f.close()
It appears to me that you haven't closed your output file properly. You should either use
with open('teste{:d}.txt', 'a') as file:
...
in which case with statement will handle closing the file for you. Otherwise you need to add file.close() to your current code.

Unable to find string in text file

I am trying to simple find if a string exists in a text file, but I am having issues. I am assuming its something on the incorrect line, but I am boggled.
def extract(mPath, frequency):
if not os.path.exists('history.db'):
f = open("history.db", "w+")
f.close()
for cFile in fileList:
with open('history.db', "a+") as f:
if cFile in f.read():
print("File found - skip")
else:
#with ZipFile(cFile, 'r') as zip_ref:
#zip_ref.extractall(mPath)
print("File Not Found")
f.writelines(cFile + "\n")
print(cFile)
Output:
File Not Found
C:\Users\jefhill\Desktop\Python Stuff\Projects\autoExtract\Test1.zip
File Not Found
C:\Users\jefhill\Desktop\Python Stuff\Projects\autoExtract\test2.zip
Text within the history.db file:
C:\Users\jefhill\Desktop\Python Stuff\Projects\autoExtract\Test1.zip
C:\Users\jefhill\Desktop\Python Stuff\Projects\autoExtract\test2.zip
What am I missing? Thanks in advance
Note: cFile is the file path shown in the output and fileList is the list of both the paths from the output.
You're using the wrong flags for what you want to do. open(file, 'a') opens a file for append-writing, meaning that it seeks to the end of the file. Adding the + modifier means that you can also read from the file, but you're doing so from the end of the file; so read() returns nothing, because there's nothing beyond the end of the file.
You can use r+ to read from the start of the file while having the option of writing to it. But keep in mind that anytime you write you'll be writing to the reader's current position in the file.
I haven't tested the code but this should put you on the right track!
def extract(mPath, frequency):
if not os.path.exists('history.db'):
f = open("history.db", "w+")
f.close()
with open('history.db', "rb") as f:
data = f.readlines()
for line in data:
if line.rstrip() in fileList: #assuming fileList is a list of strings
#do everything else here

File or directory not found even though it exists

this is my code to open a file and get the text from it :
f = open("C:/Users/muthaharsh/Documents/Harsh/News
Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-
Mint.txt","r+")
text = f.readlines()
print(text)
but i keep getting the error :
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/muthaharsh/Documents/Harsh/News Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-Mint.txt'
What code do i write to be able to do this ?
Thanks in advance ...
It's the whitespace in the path to file. Either use
r"C:/Users/muthaharsh/Documents/Harsh/News Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-Mint.txt"
or remove the whitespace in the filepath.
If you are running the code on windows add r before your filepath string.
Another way is that you can provide your input file as system arguments.
import sys
file_name = sys.argv[1]
with open(file_name, 'r') as f1:
file_text = f1.read()
print(file_text)
eg: python program for reading the file
you can run the code considering script is saved as readFile.py:
D:\Programs>python readFile.py D:\test.txt
output: This is a sample file
Here is the text

python environment file open plus path

In environmental variables in system I have defined two variables:
A_home=C:\install\ahome
B_home=C:\install\bhome
following script is written to read information from location of variable A close it, then open location of variable B and write it there, thing is script only works with precise path e.g
C:\install\a\components\xxx\etc\static-data\myfile.xml
C:\install\b\components\xxx\etc\static-data\myfile.xml
problem is, that i need python to read path that is defined in env variable, plus common path like this: %a_home%\a\components\xxx\etc\static-data\myfile.xml`
so far i have this, and i cant move forward .... anyone have any ideas?? this script reads only exact path...
file = open('C:\install\a\components\xxx\etc\static-data\myfile.xml','r')
lines = file.readlines()
file.close()
file = open('C:\install\b\components\xxx\etc\static-data\myfile.xml','w')
for line in lines:
if line!='</generic-entity-list>'+'\n':
file.write(line)
file.write('<entity>XXX1</entity>\n')
file.write('<entity>XXX2</entity>\n')
file.write('</generic-entity-list>\n')
file.close()
Try something like this:
import os
import os.path
home = os.getenv("A_HOME")
filepath = os.path.join(home, "components", "xxx", "etc", "static-data", "GenericEntityList.xml")
with open(filepath, 'r') as f:
for line in f:
print(line)
so finally success Thanks Tom, i was inspired by you ....
here goes
import os
path1 = os.environ['SOME_ENVIRO1']
path2 = os.environ['SOME_ENVIRO2']
file = open(path1 +'\\components\\xxx\etc\\static-data\\GenericEntityList.xml', 'r')
lines = file.readlines()
file.close()
file = open(path2 +'\\components\\xxx\\etc\\static-data\\GenericEntityList.xml', 'w')
for line in lines:
if line!='</generic-entity-list>'+'\n':
file.write(line)
file.write('<entity>ENTITY1</entity>\n')
file.write('<entity>ENTITY2</entity>\n')
file.write('</generic-entity-list>\n')
file.close()

how to make a .text file in terminal python3.33

I was wondering how to make a .text file so I can put words in it and then in my program open the file. I just need to know how to make a .text file!
Anyone know why my code won't open my .txt file when I try to run it?
def readWords(filename):
words = []
wordFile = open(words.txt, "r")
for line in wordFile:
line = line.upper()
words.extend(string.split(line))
wordFile.close()
return words
with open('myfile.txt', 'w') as f:
f.write('potato')
Opening a file in write mode will create it for you if it doesn't already exist:
with open("/path/to/file.txt", "w") as myfile:
# Do whatever
In the above code, myfile will be the file object.
Here is a reference on open and one on with.

Categories