How to read n number of files in n variables and then add those variables in a list?

how to create nested list in python
python list
how to add a number in a list python
python list of lists
create list of lists python
for loop python
list comprehension || python
append python

This is my code:

file_input1 = open('Amazon_Indi_Seller.py', 'r')
f1 = file_input1.read().lower()

file_input2 = open('Amazon_Prices.py', 'r')
f2 = file_input2.read().lower()

documents = [f1, f2]
import nltk, string, numpy

stemmer = nltk.stem.porter.PorterStemmer()

lemmer = nltk.stem.WordNetLemmatizer()
def LemTokens(tokens):
    return [lemmer.lemmatize(token) for token in tokens]
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
def LemNormalize(text):
    return 
LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))

from sklearn.feature_extraction.text import CountVectorizer
LemVectorizer = CountVectorizer(tokenizer=LemNormalize, 
stop_words='english')
LemVectorizer.fit_transform(documents)

Instead of reading 2 files i want to read all the files in a directory. And read them individually so that later I can add those variables in a list named documents.

You can use the code mentioned below,

  import os

    def read_files(file):
        file_input1 = open(file, 'r')
        f1 = file_input1.read()
        return f1

    files = ['sample.py', 'Amazon_Indi_Seller.py']
    data = list()
    for file in files:
        data.append(read_files(file))
    print(data)

The above code will used to read the files mentioned in the list

import os

def read_files(file):
    file_input1 = open(file, 'r')
    f1 = file_input1.read()
    return f1

src = r'DIRECTORY PATH'
data = list()
for file in os.listdir(src):
    data.append(read_files(file))

print(data)

And the above code will read all the files from the directory mentioned

Ruby Cookbook, If you want to pick a lot of random lines from a file, reading the entire file into memory The following code uses the special variable $., which holds the number of the line Assume that the algorithm works for a file of n lines: that is, each of the first n lines has a Then, add another line to the file and process the new line. Another variable, called file_count, is defined. This variable takes its value from a command substitution. This is the command phrase between the parentheses $( ). Note there’s a dollar sign $ before the first parenthesis. This construct $( ) evaluates the commands within the parentheses, and then returns their final value. In this example, that value is assigned to the file_count variable.

You could collect all the in a list, for example: lst = []

 for file in os.listdir():
     file_input = open(file,"r")
     lst.append(file_input.read())

One extra recommendation - in general it might be wise to store the contents of a file as a collection of its lines by for example using file_input.readlines() which returns a list of lines.

11. Lists, numbers[2] Traceback (most recent call last): File "<interactive input>", line 1, in <​module> Each time through the loop, the variable i is used as an index into the list, “first evaluate the right hand side, then assign the resulting value to the variable”. result = [] for i in range(2, n): if is_prime(i): result.append(i) return result  In order to read information from a file, or to write information to a file, your program must take the following actions. 1) Create a variable to represent the file. 2) Open the file and store this "file" with the file variable. 3) Use the fprintf or fscanf functions to write/read from the file.

Create a list of all filenames and then iterate over filename list and add their content in a dictionary.

from collections import defaultdict    #imported default dictionary

result = defaultdict()    #created empty default dictionary
filenames = ['name1.py', 'name2.py', 'name3.py']   #added filenames to a list

for name in filenames:   #iterate over filename list
    with open(name, 'r') as stream:   #open each file
        data = stream.readlines()     #read contents lines by line (readlines return list of lines)
        result[name] = data    # set name as key and content as value in dictionary

print(result)   

In this way you will have a dictionary with keys as filenames and values as their contents

Dynamics and Control of Nuclear Reactors, the simout variable #n, where n is the integer defining the variable number. plot​(tout add symbols, or add color to the graph. Define all the matrices, for example, A, B, C, and D. Then save as follows in A B C D • Before starting the simulation load the stored file. Disable the block marked 'list data points to last'. This chapter describes the awk command, a tool with the ability to match lines of text in a file and a set of commands that you can use to manipulate the matched lines. In addition to matching text with the full set of extended regular expressions described in Chapter 1, awk treats each line, or record, as a set of elements, or fields, that can be manipulated individually or in combination.

If the directory may include other directories with files, which you want to read to - use os.walk

Here is sample code from the official documentation:

import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print root, "consumes",
    print sum(getsize(join(root, name)) for name in files),
    print "bytes in", len(files), "non-directory files"
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

Sams Teach Yourself Perl in 21 Days, In this case, if the user typed exit at the 'Enter the number' prompt, the last command variable, and the syntax for reading input from files on the Perl command line. #hash) { print "Key: $ value: $hash{S_}\n"; } Many functions will also use the this: print; Then, mentally add the $ on the end of it: print $ 5 The $ variable is  You can use any of the supported expressions for setting a variable. Here is an example of setting a variable to act as a counter that starts at 100, gets incremented by 1 for every run, and gets reset to 100 every day. jobs: - job: variables: a: $[counter(format('{0:yyyyMMdd}', pipeline.startTime),

Lists - Learn Python 3, n = int(input()) # read number of element in the list then the number of elements is read, then you read the list items line by line and append to the end. The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines. The history file is also truncated to this size after writing it when an interactive shell exits. The default value is 500.

Loops and lists, A Python list can be used to represent such a group of numbers in a program. With a variable that refers to the list, we can work with the whole group at We then start with an empty list and use a while loop to append one element at a time​: with the last element degrees[n-1] (if n denotes the number of elements in the list,  The general method is to make a declared variables list then test each variable entry to see if it is used. The project string contains all of the code in the project. The string is loaded into a work array line by line, and is passed in variants from process to process. Procedure, module, and project name information is also added.

Python Intro: Reading and Writing Text Files, Writing files allows us to process our data and then save the output to a file so we can with a comma-delimited text file (.csv) that contains several columns of data. Once we have read the data in the file into our variable data, we can treat it infile.readlines() will read all of the lines into a list, where each line of the file is  I have 2 variables. Both are values between 0 and 98. I want to create 1 new variable that is the total of the 2 separate variables. The variables are survey responses asking about the number of drinks consumed daily. All I want is a total variable that incorporates all of the responses from the 2 variables. They don't need to be matched.

Comments
  • Iterate file list and store file objects in dictionary, you can store objects in list as dict.values() after that
  • Try using with open('filename', 'r') as f: #todo is more pythonic. Then you don't need to .close() it.
  • It doesn't let open any file. Error is "No such file or directory"