I am trying to import a text with a list about 10 words.
import words.txt
That doesn't work...
Anyway, Can I import the file without this showing up?
Traceback (most recent call last):
File "D:/python/p1.py", line 9, in <module>
import words.txt
ImportError: No module named 'words'
Any sort of help is appreciated.
You can import modules but not text files. If you want to print the content do the following:
Open a text file for reading:
f = open('words.txt', 'r')
Store content in a variable:
content = f.read()
Print content of this file:
print(content)
After you're done close a file:
f.close()
As you can't import a .txt file, I would suggest to read words this way.
list_ = open("world.txt").read().split()
The "import" keyword is for attaching python definitions that are created external to the current python program. So in your case, where you just want to read a file with some text in it, use:
text = open("words.txt", "rb").read()
This answer is modified from infrared's answer at Splitting large text file by a delimiter in Python
with open('words.txt') as fp:
contents = fp.read()
for entry in contents:
# do something with entry
numpy's genfromtxt or loadtxt is what I use:
import numpy as np
...
wordset = np.genfromtxt(fname='words.txt')
This got me headed in the right direction and solved my problem.
Import gives you access to other modules in your program. You can't decide to import a text file. If you want to read from a file that's in the same directory, you can look at this. Here's another StackOverflow post about it.
Related
I am very fresh in Python. I would like to read JSON files in Python, but I did not get what are the problems. Please see the image.
You have to specify a mode to the open() function. In this case I think you're trying to read the file, so your mode would be "r". Your code should be:
with open(r'path/to/read/','r') as file:
data = json.load(file)
Your code should run now.
Your path should not contain spaces. Please modify the file path.
Generally speaking, the file path is best to be in full English with no spaces and no special characters.
import sys
import os
import json
def JsonRead(str):
with open(str, encoding='utf-8') as f:
data = json.load(f)
return data
new_Data = JsonRead(filePath)
Then import JsonRead in project
I would like some help using python to open a file and use the contents of the file as a variables.
I have a script that looks like this.
#!/usr/bin/env python
with open("seqnames-test1-iso-legal-temp.txt") as f:
gene_data = {'ham_pb_length':2973, 'ham_pb_bitscore':5664,'cg2225_ph_length':3303, 'cg2225_ph_bitscore':6435,'lrp1_pf_length':14259, 'lrp1_pf_bitscore':28010,}
for line in f:
if not line.isspace():
bitscore = gene_data[line.rstrip()+'_bitscore']
length = gene_data[line.rstrip()+'_length']
if (2*0.95*length <= bitscore/2 <= 2*1.05*length):
print line
Where the file "seqnames-test1-iso-legal-temp.txt" is a list of gene names ham_pb, cg2225, lrp1_pf, etc. I only included the first 6 values of the dictionary, but it has a total of 600 keys. Each in the form 'name'_length, 'name'_bitscore for the 300 gene names in the file "seqnames-test1-iso-legal-temp.txt".
For this reason, I would like to save the dictionary gene_data as a separate text file, and read the file while executing the script. Is there a way to do this. I tried to make a text file "gene_data1.txt" that just included the dictionary. So, the contents of the text file are:
gene_data = { 'ham_pb_length':2973, 'ham_pb_bitscore':5664,'cg2225_ph_length':3303, 'cg2225_ph_bitscore':6435,'lrp1_pf_length':14259, 'lrp1_pf_bitscore':28010,}
And I tried to use the open function to open the file, so my script looked like this:
#!/usr/bin/env python
gene_data = open("gene_data1.txt", "r")
with open("seqnames-test1-iso-legal-temp.txt") as f:
for line in f:
if not line.isspace():
bitscore = gene_data[line.rstrip()+'_bitscore']
length = gene_data[line.rstrip()+'_length']
if (2*0.95*length <= bitscore/2 <= 2*1.05*length):
print line
But this just gave me the error message:
Traceback (most recent call last):
File "fixduplicatebittest1.py", line 6, in <module>
bitscore = gene_data[line.rstrip()+'_bitscore']
NameError: name 'gene_data' is not defined
Is there a simple way to make this script?
Any help would be greatly appreciated.
You can replace this line:
gene_data = open("gene_data1.txt", "r")
with this:
import ast
with open('dict.txt') as f:
gene_data = f.read()
gene_data = ast.literal_eval(gene_data)
but make sure the text file just contains the dictionary, not the assignment of the dictionary:
{ 'ham_pb_length':2973, 'ham_pb_bitscore':5664,'cg2225_ph_length':3303, 'cg2225_ph_bitscore':6435,'lrp1_pf_length':14259, 'lrp1_pf_bitscore':28010,}
As pointed out by others, allowing your script to execute any command in a file can be dangerous. With this method, at least it won't execute anything in the external file, if the contents don't evaluate nicely the script will just throw an error.
The simplest way would be to put the dictionary as you wrote it in its own .py file and import it like any other module.
from <filename without .py> import gene_data
Then you can use it as if you had typed it in the importing module.
This is very unsafe to do if you do not control the data file.
Either execfile or import will let you run it as text inside your file. Be mindful of security implications though. import gives you more control over the execution process, but at the expense of more involved syntax.
import ast
dict_from_file=[]
with open('4.txt', 'r') as inf:
dict_from_file = ast.literal_eval(inf.read())
File "<unknown>", line 1
["hello":"work", "please":"work"]
^
SyntaxError: invalid character in identifier
Hi Everyone! The above is my code and my error. I have a really complicated 40MB data file in the form of a dictionary to work on, but couldn't get that import to work so tried a simple one.
I'm using the latest Jupyter notebook from the latest version of Anaconda, on Windows 10. My dictionary is a txt file created using windows notepad. The complicated dictionary was originally a JSON file that I changed into a txt file thinking it would be easier but I may be wrong.
I think the above error is an encoding issue? But not sure how to fix it.
Thanks!
If you are the owner/write of the file (dict formated), save as json
import json
#To write
your_dict = {.....}
with open("file_name.txt", "w+") as f:
f.write(json.dumps(your_dict)
#To read
with open("file_name.txt") as f:
read_dict = json.load(f)
This is possibly a python 3 "feature".
This code removes the unwanted characters at the start of the input file and returns the input data as type string.
with open('4.txt', 'r',,encoding="utf-8-sig") as inf:
dict_from_file = ast.literal_eval(inf.read())
This removes the strange characters put at the beginning of read data.
I'm attempting to read a CSV file and then write the read CSV into another CSV file.
Here is my code so far:
import csv
with open ("mastertable.csv") as file:
for row in file:
print row
with open("table.csv", "w") as f:
f.write(file)
I eventually want to read a CSV file write to a new CSV with appended data.
I get this error when I try to run it.
Traceback (most recent call last):
File "readlines.py", line 8, in <module>
f.write(file)
TypeError: expected a character buffer object
From what I understood it seems that I have to close the file, but I thought with automatically closed it?
I'm not sure why I can write a string to text but I can't simply write a CSV to another CSV almost like just making a copy by iterating over it.
To read in a CSV and write to a different one, you might do something like this:
with open("table.csv", "w") as f:
with open ("mastertable.csv") as file:
for row in file:
f.write(row)
But I would only do that if the rows needed to be edited while transcribed. For the described use case, you can simply copy it with shutil before hand then opening it to append to it. This method will be much faster, not to mention far more readable.
The with operator will handle file closing for you, and will close the file when you leave that block of code (given by the indentation level)
It looks like you intend to make use of the Python csv module. The following should be a good starting point for what you are trying to acheive:
import csv
with open("mastertable.csv", "r") as file_input, open("table.csv", "wb") as file_output:
csv_input = csv.reader(file_input)
csv_output = csv.writer(file_output)
for cols in csv_input:
cols.append("more data")
csv_output.writerow(cols)
This will read mastertable.csv file in a line at a time as a list of columns. I append an extra column, and then write each line to table.csv.
Note, when you leave the scope of a with statement, the file is automatically closed.
The file variable is not really actual file data but it is a refernce pointer which is used to read data. When you do the following:
with open ("mastertable.csv") as file:
for row in file:
print row
file pointer get closed automatically. The write method expects a character buffer or a string as the input not a file pointer.
If you just want to copy data, you can do something like this:
data = ""
with open ("mastertable.csv","r") as file:
data = file.read()
with open ("table.csv","a") as file:
file.write(data)`
I'm very new to programming (obviously) and really advanced computer stuff in general. I've only have basic computer knowledge, so I decided I wanted to learn more. Thus I'm teaching myself (through videos and ebooks) how to program.
Anyways, I'm working on a piece of code that will open a file, print out the contents on the screen, ask you if you want to edit/delete/etc the contents, do it, and then re-print out the results and ask you for confirmation to save.
I'm stuck at the printing the contents of the file. I don't know what command to use to do this. I've tried typing in several commands previously but here is the latest I've tried and no the code isn't complete:
from sys import argv
script, filename = argv
print "Who are you?"
name = raw_input()
print "What file are you looking for today?"
file = raw_input()
print (file)
print "Ok then, here's the file you wanted."
print "Would you like to delete the contents? Yes or No?"
I'm trying to write these practice codes to include as much as I've learned thus far. Also I'm working on Ubuntu 13.04 and Python 2.7.4 if that makes any difference. Thanks for any help thus far :)
Opening a file in python for reading is easy:
f = open('example.txt', 'r')
To get everything in the file, just use read()
file_contents = f.read()
And to print the contents, just do:
print (file_contents)
Don't forget to close the file when you're done.
f.close()
Just do this:
>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
... print f.read()
This will print the file in the terminal.
with open("filename.txt", "w+") as file:
for line in file:
print line
This with statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for loop
How to read and print the content of a txt file
Assume you got a file called file.txt that you want to read in a program and the content is this:
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line
You can read this content: write the following script in notepad:
with open("file.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
save it as readfile.py for example, in the same folder of the txt file.
Then you run it (shift + right click of the mouse and select the prompt from the contextual menu) writing in the prompt:
C:\examples> python readfile.py
You should get this. Play attention to the word, they have to be written just as you see them and to the indentation. It is important in python. Use always the same indentation in each file (4 spaces are good).
output
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line
to input a file:
fin = open(filename) #filename should be a string type: e.g filename = 'file.txt'
to output this file you can do:
for element in fin:
print element
if the elements are a string you'd better add this before print:
element = element.strip()
strip() remove notations like this: /n
print ''.join(file('example.txt'))
This will give you the contents of a file separated, line-by-line in a list:
with open('xyz.txt') as f_obj:
f_obj.readlines()
It's pretty simple
#Opening file
f= open('sample.txt')
#reading everything in file
r=f.read()
#reading at particular index
r=f.read(1)
#print
print(r)
Presenting snapshot from my visual studio IDE.
single line to read/print contents of a file
reading file : example.txt
print(open('example.txt', 'r').read())
output:
u r reading the contents of example.txt file
Reading and printing the content of a text file (.txt) in Python3
Consider this as the content of text file with the name world.txt:
Hello World! This is an example of Content of the Text file we are about to read and print
using python!
First we will open this file by doing this:
file= open("world.txt", 'r')
Now we will get the content of file in a variable using .read() like this:
content_of_file= file.read()
Finally we will just print the content_of_file variable using print command.
print(content_of_file)
Output:
Hello World! This is an example of Content of the Text file we are about to read and print
using python!